text:
How to set sampling rate for digital pin input?
I have an ADC that have sampling rate up to 40 MSPS, but i use 8 MHz clock so it will be 8 MSPS. The board used is arduino nano. The problem is i have to sampling it just 2 MHz (because the capacity of array variable in arduino Nano, which is around 10.000 elements in array variable). I know that using direct port reading will increase the speed of the digital read, but how can i set the direct port reading to just read every 0.5 us? Micros function cannot do the job of course
Thank you

On what board...?

@Majenko edited, Arduino Nano

You don't set the sampling rate for a digital pin. You sample it in software by readinging the appropiate PORTX register (C,D,..). 500 nanoseconds is pretty on the edge. Only reading the PORT will cost you 125ns (and that's NOT doing any SPI logic -- if you bitbang SPI then this will be ONE BIT!) (https://github.com/NicksonYap/digitalWriteFast/blob/master/NOTES/NOTES.md)

@MaximilianGerhardt how can i set it in the software? AFAIK, using timer wont work because there is no timer with resolution 500ns

You can sample a digital port at 2 MHz, or even as fast as F_CPU/3, while storing the data in an array, but: 1. This needs assembly programming and, 2. It is very likely not what you want to achieve.

Of course, sampling too quickly will not allow the internal capacitor to stabilize at the input voltage.  I agree with @MaximilianGerhardt that 500 ms is a reasonable speed, determined by delay().

You need:

A timer
A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.
At 16MHz you get a clock period of 63ns.  That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's at most 8 assembly instructions that can be executed within that time.
Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there.  No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a long time compared to 500ns.
So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.

Note: this is an attempt to answer the question as asked. This
answer is unlikely to be of any use to the original poster, who
presumably asked the wrong question. I am writing this only as a way to
explore the limits on how fast a modest AVR can sample a port. For an
answer that genuinely attempts to address the OP’s problem, see
Majenko’s answer.
I read the question as follows: can we sample a digital port at
2 MHz on an Arduino Nano clocked at 8 MHz? Can we do so while
storing the values in a RAM-based buffer?
The answer is yes, but it is non trivial, and it requires some assembly.
To see the problem, let’s start by trying to do it in C++:
uint8_t buffer[1024];

void fill_buffer()
{
    cli();
    for (size_t i = 0; i < sizeof buffer; i++)
        buffer[i] = PINB;
    sei();
}

Note that the loop runs with interrupts disabled, otherwise the timer
interrupt would wreak havoc with the loop timing. This is translated by
gcc into an assembly equivalent to this:
    cli
    ldi  r30, lo8(buffer)      ; load the buffer address into pointer Z
    ldi  r31, hi8(buffer)      ; ditto
0:  in   r24, 0x03             ; read the port
    st   Z+,  r24              ; store into buffer, increment the pointer
    ldi  r24, hi8(buffer+1024) ; save (buffer+1024)>>8 in r24
    cpi  r30, lo8(buffer+1024) ; compare the pointer with buffer+1024
    cpc  r31, r24              ; ditto
    brne 0b                    ; loop back
    sei
    ret

The loop takes 8 cycles per iteration. With an 8 MHz clock, that
would be one reading per microsecond. Too slow by a factor two.
One could save one cycle by using a different register for the port data
and for the end-of-loop condition, and by moving the third ldi out of
the loop. Another cycle could be saved by testing only the high byte of
the Z pointer, but that would require aligning the buffer to
256 byte boundaries. With those two optimizations, we still need
6 CPU cycles per iteration, i.e. 0.75 µs at 8 MHz.
In order to make this faster, the only solution is to unroll the loop.
This can be done in assembly by using the .rept (meaning “repeat”)
directive:
void fill_buffer()
{
    cli();
    asm volatile(
        ".rept %[count]\n"  // repeat (count) times:
        "in r0, %[pin]\n"   //   read the port input register
        "st Z+, r0\n"       //   store in RAM
        "nop\n"             //   1 cycle delay
        ".endr"
        ::      "z" (buffer),
        [count] "i" (sizeof buffer),
        [pin]   "I" (_SFR_IO_ADDR(PINB))
        : "r0"
    );
    sei();
}

This takes 4 cycles, or 0.5 µs per iteration. Note that a
delay cycle had to be introduced, otherwise the sampling would be too
fast : 3 cycles, or 0.375 µs, per iteration.
This is not the fastest one can get. It is possible to take one sample
per CPU cycle with something like this:
    in r0, 0x03
    in r1, 0x03
    in r2, 0x03
    ...

However this technique is limited to burst readings of at most
32 samples.


text:
minimal code for multiple buttons de-bouncing
i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...
is this function sufficient to get a debounced state of the pressed button?
byte buttonPressed(){
  byte btn = 0;
  if (digitalRead(30)==LOW) btn = 1; else
  if (digitalRead(9)==LOW) btn = 2; else
  if (digitalRead(31)==LOW) btn = 3; else
  if (digitalRead(8)==LOW) btn = 4;
  delay(20);
  return btn;
}

any strictly necessary improvements are welcome...

i write the code a-la-va-vite, thanks Edgar.

Currently there is no debouncing present in your code. The delay is completely useless.

Oops! I deleted my previous comment, which was wrong: I didn't notice your elses due to your very unconventional indent style.

Yes, your code should work as the most basic debouncing, although the
debouncing time may be a little bit short. Note however that, in many
instances, one would like to have a little more that the most basic. One
may also want:

deglitching: when the button is held down, your hand may make the
contacts move a little bit, making spikes in the reading that are not
associated with a real change in the button position; you don't want
those spikes to read as "released and pressed again"
edge detection: many times you are more interested in the button
press event than in knowing whether the button is down or up; this can
be handled by another function, but it can be convenient to integrate
it with the debouncing
non blocking operation: your program may have better things to do
than wasting CPU cycles inside delay().

Those are the reasons most debouncing codes are significantly more
complex. But it's often worth it.

Edit 1: In view of the comments, some clarification seems to be
needed. There are two kinds of glitches a mechanical button can
experience:

when the button is mechanically changing position, i.e. it is being
depressed or released; this is called a bounce
when the button is being held down, especially if the pressure on the
button is low and the finger applying that pressure is somewhat
shaky.

Most debouncing libraries you can find actually address both kinds of
glitches. Thus, they do more than just debouncing, they do what I
called “deglitching”. The previous answers implicitly assume that a
proper debouncing code must address both kinds.
The code posted in the question only addresses the first kind of
glitches, i.e. the bounces in the strict sense. That's why I wrote
that it does the “most basic debouncing”. It is however susceptible to
the second kind of glitches. So yes, with this code glitches can persist
even after debouncing.
Edit 2: As an example, consider the Bounce 2 library. It
provides edge detection, non blocking operation and, in the default
configuration, full deglitching. However, it can be configured to use
an alternative debounce algorithm called “Lock-out
interval”, which is more responsive but does not protect against the
“type 2” glitches mentioned above: it “does not cancel noise”, as the
documentation puts it.

is there any relation between deglitching and debouncing?...

@moyoumos: A bounce is just a specific kind of glitch that happens while the button is being depressed or released. If you do deglitching, e.g. by waiting until a level is stable, you are also debouncing. The converse is not true: the code you posted removes bounces but it does not properly clean glitches that happen while the button is held down.

according to what you say glitchs can exist or persist even after debouncing!!!

@moyoumos: Yes, see amended answer.

i think that any debouncing algorithm based on a time interval can't do de-glitching since bounces (or glitchs) persist after this time interval!!! am i wrong?

@moyoumos: Time-based deglitching is based on the premise that if the button has been giving a consistent reading throughout a given time interval, then that reading is not a glitch (glitches are short).

While @MichelKeijzers answer is a nice solution for simple querying in the main loop. This is not practicable for interrupts. Interrupts can block the entire MCU and interrupting an interrupt routinte can cause serious problems.
Depending on your requirements I'd suggest to take a look at using capacitors and resistors for debouncing. With that you achieve simpler code and no need for dealing with hardware issues in software. Of course at the expense of additional parts in your hardware setup.
If your MCU for example is using a pin as interrupt, that interrupt would be called only once as opposed to bouncing one.

No - simply delay()ing after reading the button doesn't tell you whether the button is still bouncing or, more importantly, what its final state is. Debouncing requires you to know that the button

changed state;
has stopped changing state;
what state it has settled into.

You'll need to notice the current state doesn't match the last debounced state you saw; then either test it frequently until it doesn't change state again for some number of tests, or simply wait the known maximum time it takes to settle; then read, store, and return the final state.

No. Actually it just checks each button one by one. In addition only the last button is checked since it overwrites the btn variable.
The simplest way to use debouncing button 1 is:
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    delay(50); // Wait 50 ms, or 100 depending on your debouncing time
    byte btn1After = digitalRead(30);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
        btn = 1;
    }
}

You have to do similar as the others. You can use only one delay (just add 4 before and after variables and check them.
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    byte btn2Before = digitalRead( 9);
    byte btn3Before = digitalRead(31);
    byte btn4Before = digitalRead( 8);

    delay(50); // Wait 50 ms, or 100 depending on your debouncing time

    byte btn1After = digitalRead(30);
    byte btn2After = digitalRead( 9);
    byte btn3After = digitalRead(31);
    byte btn4After = digitalRead( 8);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
       btn = 1;
    }
    else if ((btn2Before == LOW) && (btn2After == LOW))
    {
       btn = 2;
    }
    else if ((btn3Before == LOW) && (btn3After == LOW))
    {
       btn = 3;
    }
    else if ((btn4Before == LOW) && (btn4After == LOW))
    {
       btn = 4;
    }

    return btn;
}

Note that this way the program will be unresponsive for 50 ms. If you do not want this, you have to use millis, but this makes it more complex. Check the debouncing example on the Arduino site.

why check the before and after state of the button?...

By checking that the state again after the debounce time (I chose 50 ms). If the debouncing is finished, it will show twice LOW.

i think that if the hardware detects the first LOW it's because the button is Pressed, then a delay (20 or 50ms..) is sufficient to ignore all bounces!!...

I wanted to stick to the original program. If no interrupts are used, this way the priority can be changed by software.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
comparison in a time sequence
in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM,  this number is to be added at the end of an ordered and limited sequence of times
--the first input (lower limit) can be any time within the 24 hours,
--the upper limit is calculated as lower_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,
--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;
for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.
without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.
any link, or tip,...

Are the numbers inputted via Serial? On the first example, is it correct that any time from inclusive 20:01 to 04:00 will be accepted?

This smacks of homework to me....

Tip: work in minutes. The modulus (%) operator is your friend.

@maximilian-gerhardt: numbers are inputted via buttons... any number from 20:01 to 04:00 are accepted if it's chronologically after the last element before the upper limit...

You have numerous problems here - how to enter the times, how to convert that entered time into minutes, how to compare those times properly. Tackle it one thing at a time.

So you said you already solved the problem?

@majenko: sorry  i didn't give anough information... the only problem is how to compare those times properly...

@maximilian-gerhardt: working in minutes give a simple representation of the times but did not solve the problem... applied to the example the upper limit is still inferior to the lower limit: [20:00 to 04:00] becomes [1200 to 240]...

if (start < end) { // check if it's greater than start *and* less than end } else { // check if it's greater than start *or* less than end }

Here is the basic idea and a sample implementation for solving the problem:
The problem is: Given a start time time1 and a period period, each described by a pair of (hour,minute), how can we check whether another time time2 is within time1 to time1 + period?
First we can see that we given a (hour, minute) pair we can compute the total number of minutes as totalMinutes = 60*hour + minute.
Then we can observe that there two distinct cases that we must check:

the entire "time check period", that is, time1 to time1 + period is within 00:00 to 24:00 without overflowing past 24:00 when we simply add the times. then, we can use a simple bounds check worded as "time2 must be greater than time1 and less or equal to time1 + period when comparing total minnutes.
time1 + period overflows past 24:00. We consider an example of  time1= 20:00 and period = 8:00. Thus all valid times are from 20:00 to 04:00 with an implicit "wrap around" at 24:00 to 00:00. We can see that there are now two time-intervals we must check: Everything from 20:01 to 24:00 and from 00:00 to 04:00 is valid. Thus we can derive the the bounds in minutes again. We can obtain the 04:00 by computing 20:00 + 08:00 modulo 24:00. The C operator % is used to compute the residue of the division by a certain number. I.e. 28 % 24 = 4 because 28 / 24 = 1 residue 4. This is  called modulo-arithmetic.

The following C++ program demonstrates the solution:
#include <cstdio>

/* returns whether time2 defined by hour2:minute2 is within the period time1 = hour1:minute1 to time1 + period. */
bool is_time_within_period(
    int hour1, int minute1,
    int hour2, int minute2,
    int periodHour, int periodMinute) {

        //Reject garbage input
        if(hour1 > 24 || hour2 > 24
            || minute1 > 60 || minute2 > 60
            || periodHour > 24 || periodMinute > 60) {
                //TODO throw error message
                return false;
        }

        //Convert hours and minutes into absolute minutes. One hour is 60 minutes.
        int time1Minutes = 60 * hour1  + minute1;
        int periodMinutes = 60 * periodHour + periodMinute;
        int time2Minutes  = 60 * hour2 + minute2;

        int periodEnd = time1Minutes + periodMinutes;

        //If the start time plus the period time is over 24:00 there is a wrap-around the we need to consider.
        bool wrapAround = false;
        if( periodEnd > (24 * 60)) {
            wrapAround = true;
        }

        bool result = false;

        //printf("Wrap: %d Period end %d\n", wrapAround, periodEnd);

        if(!wrapAround) {
            //if there is no wrap-around we can just compare the total minutes against each other
            //time1 must be after time2 but before (time1 + period).
            result = time2Minutes <= (time1Minutes + periodMinutes) && time2Minutes > time1Minutes;
        } else {
            //There was a wrap around, i.e. start time + period was beyond 24:00.
            //We need to make two comparisons: is it in the time period from time1Minutes to 24:00?
            result = time1Minutes < time2Minutes && time2Minutes <= (24 * 60);

            //the result can also be okay if it from the time from 00:00 to the remaining period
            //use the module operator here. This transforms e.g. 28:00 would be reduced to 04:00. (modulo 24 hours calculated in minutes)
            int upper = (periodEnd % (24 * 60));
            //printf("Upper: %d (%02d:%02d)\n", upper, (upper / 60), upper % 60);
            result |= time2Minutes >= 0 && time2Minutes <= upper;
        }

        return result;
}

int main() {

    const int hourStart = 20;
    const int minuteStart = 0;

    const int periodHours = 8;
    const int periodMinutes = 0;

    //play around with these values
    const int compareTimeHour  = 4;
    const int compareTimeMinute = 0;

    printf("Start: %02d:%02d\n", hourStart, minuteStart);
    printf("Period: %02d:%02d\n", periodHours, periodMinutes);
    printf("Check time: %02d:%02d\n", compareTimeHour, compareTimeMinute);

    bool res = is_time_within_period(hourStart, minuteStart, compareTimeHour, compareTimeMinute, periodHours, periodMinutes);

    if(res) {
        printf("Time is within bounds\n");
    } else {
        printf("Time is not within bounds\n");
    }

    printf("Hello\n");

    return 0;
}

The function is_time_within_period has no dependencies and can thus be copy-pasted into any Arduino sketch.
Let the start time be 20:00 and the period 04:00. Then feeding the program different times to compare against lets us see that it indeed works.
Start: 20:00
Period: 08:00
Check time: 20:00
Time is not within bounds

Start: 20:00
Period: 08:00
Check time: 20:01
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:00
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:01
Time is not within bounds

it was very simple: if there is a wrap-around in the comparison interval; then we divide this interval in two at the point of this wrap-around... thanks and +5...

The function is_time_within_period has no dependencies and can thus be copy-pasted into any Arduino sketch.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Analog inputs showing value even there is nothing connected to it
After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.
the code is
float ana [] = {A0,A1,A2,A3,A4,A5};
float dec [6];

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

void loop()
{
  for(int i = 0; i<6 ; i++)
  {
    dec[i] = analogRead(ana[i]);
    Serial.println(dec[i]);
    delay(1000);
  }
}

How is this even possible?
this is the output result

You have an array of 6 analog pins, but are reading from 7.

It was a mistake.. i corrected it

read the docs https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/ section "Notes and Warnings"

Your input is floating if nothing is connected.  It is reading whatever random noise it happens to pick up.  That's what it is supposed to do.  For it to read 0 it would need to be connected to ground.  Google "floating input" for more info.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

Most of what follows has already been covered in previous answers. I am
posting this nevertheless because I feel no answer so far makes the
whole story clear enough. Let me break down the question into two
sub-questions.
1. How can I get non-ASCII characters correctly print on the serial monitor?
The answer is simply send them as UTF-8.
That's really all there is to it. The serial monitor expects you to send
UTF-8, and it will print the characters correctly only if you use this
encoding. But that brings the second question:
2. How can I get the characters as UTF-8 in my Arduino program?
Here you have several options:
Option 1: encode them yourself
For example, the Greek letter “μ” (U+03BC) in UTF-8 is (0xce 0xbc). You
can send those bytes explicitly, like
Serial.write(0xce);
Serial.write(0xbc);

or, more comfortably, like
Serial.print("\xce\xbc");

The second syntax is more convenient because it allows the character to
be embedded within a longer string.
Option 2: let the Arduino IDE encode them
If you can get the characters in the IDE's editor window, either with an
appropriate keyboard layout or by copying and pasting from another
application, then you can use them as is in the string:
Serial.print("μ");

The editor will save the source code as UTF-8, and those UTF-8 bytes
will go undisturbed from the source file to the compiled program, to the
Arduino memory, to the serial port, and finally to the serial monitor.
This option is the best for readability. However, it is somewhat
fragile: if the source code ever gets re-encoded (e-mail clients and
servers sometimes do that), then the resulting program will not work as
expected.
Options 3: let the compiler encode them
You can ask the compiler to do the UTF-8 encoding for you with the
syntax
Serial.print(u8"\u03bc");

Here, the escape sequence \u03bc is a way to represent the Unicode
character U+03BC (i.e. “μ”), and the u8 prefix means that you want the
string as a byte array encoded in UTF-8.
Note that, in practice, the u8 prefix is not needed, as the gcc
compiler assumes UTF-8 by default. I would keep the prefix anyway
because it doesn't hurt to make the encoding explicit, and it may avoid
angering some language lawyer...
Note also that the syntax above only works for characters U+0000 through
U+FFFF, i.e. the basic multilingual plane. For other Unicode characters,
you have to use the syntax \U + 8 hex digits. For example, the
character “” (U+1F60E: smiling face with sunglasses) can be printed
with:
Serial.print(u8"\U0001f60e");

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

but then the compiler rightfully complains
error: \ud83d is not a valid universal character
error: \ude0e is not a valid universal character

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

The Serial Monitor uses Unicode, so sending characters in that format is possible.  The UTF-16 code for µ is 03BC, and you can send it by prepending \u:
Serial.print("\u03BC");

The actual stream of transformations is you provide Unicode (essentially UTF-16) in your string. C++ then converts that into a stream of 8-bit characters in UTF-8 format, which is then sent down the serial connection. Java then receives those and interprets them as UTF-8, recombining them back into the original UTF-16 characters for display in the JTextArea that comprises the Serial Monitor in the Arduino IDE.
This complex transformation is done because:

UTF-8 is easier to stream over an 8-bit data link, but is very hard to work with in a program (because of variable-length byte sequences), and
UTF-16 is hard to stream (and breaks ASCII compatibility) but is far easier to work with programmatically (since it is just fixed size 16-bit characters).

So your 0x03BC gets transformed into 0xCE,0xBC which is the UTF-8 representation of the Unicode character 0x03BC.

Comments are not for extended discussion; this conversation has been moved to chat.

It depends on your operating system, the arduino version and perhaps even on the selected board.
You have selected a weird character, because there are two versions: the micro µ and the mu μ.
See: https://en.wikipedia.org/wiki/Mu_(letter) and https://en.wikipedia.org/wiki/Micro-. They are not the same.
In linux with the Arduino 1.8.5 and Arduino Uno board, everything supports UTF-8 (the Arduino ide, the serial monitor and the ino file).
To test it, I have written the micro character with AltGr+m in the sketch. It is stored in the ino file as C2 B5, which is UTF-8. It shows in the serial monitor as µ.
With gtkterm, it shows as a µ, and in hexadecimal and it shows C2 B5. That confirms that everything is UTF-8 in linux with Arduino version 1.8.5.
The Unicode "\u03BC" shows a µ in the serial monitor. It is stored in the ino file as 5C 75 30 33 42 43. That is not UTF-8 and not UTF-16, but ASCII for the characters "\u03BC". That is okay, since that is what is typed in the sketch. With gtkterm it shows a µ and CE BC in hexadecimal mode. The CE BC is UTF-8 for mu.
That means the Unicode is translated to UTF-8. Perhaps the compiler translates it to UTF-8?
These are the only tests that I did. It is just a very small part of all possibilities.
Conclusion:
Try to type µ (mu or micro) in the Arduino ide editor.
Using AltGr+m will only work if you have selected a certain keyboard settings. Perhaps you can copy the character from the Wikipedia page.
Using Unicode "\u03BC" seems to be possible.
[ADDED]
The internal format of text in Java was UTF-16, but only a fixed two byte format, not the four bytes. It was therefor only a subset of the Unicode characters. The newest Java version supports the real UTF-16 format for user strings, and thus supports all the Unicode characters.
The data that is stored to a ino file and the data that is transmitted to the serial monitor can be ASCII for normal characters with the addition of UTF-8. Most special characters that I use require two bytes in the UTF-8 format.
For Majenko: look at the binary data of a ino file and the binairy serial data. It is not a fixed two byte per character, but just one byte for normal characters.
I still don't know who translates the Unicode description of a character to UTF-8. It would be indeed weird if the compiler did that, so somewhere Java might automatically translate that.

It depends on none of those things. It depends purely on what is receiving the raw bytes as to what you place in your sketch. Since that is Java, and Java use 16 bit UTF-16 (regardless of operating system) you embed 16 bit UTF-16 codes in your strings to display things in your serial monitor. If you are sending to something else then you embed the correct codes for whatever you are sending to. But since this is the serial monitor then it is UTF-16 and will always be UTF-16.

@Majenko , I think you need a night sleep and have a look at it again. In the past the ino file stored UTF-8 characters but the serial monitor did not accept them. The arduino version does matter. In the past there were a number of differences with UTF-8 in Windows and linux.

No one cares about UTF-8. Only UTF-16.

And saving UTF-8 in the ino file has nothing to do with sending UTF-16 to the serial monitor.


text:
Error in finding frequency of an input signal
Here is my code to find the frequency of an input rectangular wave at pin 8 of the Arduino Uno board.
const uint16_t freqPin = PB0;
const uint16_t load = 0;
unsigned long int count=0;
unsigned int value=0;

void setup()
{
Serial.begin(9600);
DDRB = 0x00;
TCCR1A = 0;
TCCR1B = TCCR1B & B11111000 | B00000111;
TCNT1 = load;
TIMSK1 |= (1<<ICIE1);
TIMSK1 |= (1<<TOIE1);
sei();
}

void loop()
{
}

ISR(TIMER1_OVF_vect){

  count++;
}
ISR(TIMER1_CAPT_vect){
  value = TCNT1;
  TCNT1 = load;
  Serial.println(count);
  Serial.println(value);
}

The output is
0
0
0
0
0

Why the output is showing zeroes only. why is this happening ? Can someone explain?
Thanks in advance.

You should add something to differentiate which ISR is printing which "0". That may give some clues.

I have edited the OVF ISR where the Serial.print command was written mistakenly.

As I remember, Serial doesn't work inside of an ISR. Am I wrong?

What frequency range are you hoping to measure?

There are a few ways to measure the frequency of the incoming signal.  Here are ideas based on the assumption that's all you want, rather than to use specific pins of the Arduino:

Use timer interrupts and digitalRead(8); (or faster (PINB & _BV(0))) to sample when the signal is high or low.  Transfer the data off Arduino, e.g. to a PC, then do a Fourier transform (Matlab, Mathematica, Excel, whatever you like).  Alternatively, calculate the frequency on-board.  This way it is possible to measure frequencies up to several tens of kHz, with a precision of few Hz.
Use attachInterrupt() on either digital pins 2 or 3.  Count the number of rising edges of the square wave within a given time period.  You can use the timer if you need accuracy, but the method will not be as good as Fourier transform.


text:
Using an Atmega8 Chip with an Arduino Uno instead of an atmega328
This question is posted here as a reference question (its actually a follows  on from comments in my earlier question "How to expand program memory on an arduino?") -( Edgar Bonet suggested this question and who answered 1 below  in the comments there).
I think its a useful question to others new to arduino. I have posted an answer too. But you can of course add your answer too. I dont know everything about arduino- still learning. It does not refer to the version of the Uno that uses a surface mount atmega328-but the version with removable atmega328.
1) If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn a bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328)?  The atmega8 is of course an older chip than the 328 (and is significantly cheaper) but it still has same pinouts.
2). I am using the 16mhz crystal in my project. So using an Arduino Uno with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino Uno pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator?
3) So hw much memory is left after writing bootlader to atmega8 ?
4) Can I burn the bootloader more than once?

1) yes the arduino uno can be used with a blanked at mega8 chip with the NG bootloader burned onto it.
You would set the board as NG in the IDE to use the arduino IDE (to upload sketches and so on) with it.
2) A crystal and capacitors is still required -the same values as used for the removed atmega328.
3) The smallest bootloader will leave 7.5kb of program memory left to use on the atmega8.
4) Yes

Part 2 of your answer doesn't apply if you edit boards.txt to match whatever oscillator settings you will use.  One can use a fuse calculator like at engbedded.com, click to select ATmega8, click to select feature and frequency combination as needed.  Edit boards.txt accordingly.

@jwpat7 I updated the question- should have mentioned Im using the crystal in the question. And your comment is useful and interesting.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to interface an arduino to load sensor with darlington transistor?
I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

You'd be better of with an opamp, if you have that.

First decide if you are trying to weigh something, design a product, understand load cells, or "golf" a TIP120 solution.  For the first, order an HX711 module, for the second or third do more research, and for the fourth see if you can find a meter stick and some string to go with your TIP120.

@Gerben Gerben I do have an lm358 opamp but isnt the gain of a tip120 sufficient? I dont have an hx711 module chris. Im trying to make a circuit that can weight betwteen 0 and 3000 grams. But I think there should be a generic circuit to do this.

Chris my understanding  of load cells is its simply a variation of a wheatstone bridge which is of course a configuration of four resistors. But it differs from the standard wheatstone bridge as the resistors are replaced by variable ones which detect strain converting to changes in rresistance-though the change is so small it needs suitable amplification. There's more to it than that of course but that basically how the sensor works.

What you have there is (or sounds like) a full wheatstone bridge.
You require either a special amplifier (such as the HX711) or a highly sensitive and accurate differential ADC (such as the MCP3428 - (on  a shield)).

Ok Ill try and get the HX711 or MC3428 if I can. Yes I think it is a full wheat stone bridge too. But cant you build it without special parts? Even just to detect rough weight measurements? I have lm358, tip120  to build it?

The best you could hope for is to build an instrumentation amplifier which consists of (at least) three op-amps. Yes, you could build an op-amp out of transistors and resistors, but it's far from easy (I wouldn't like to try it). Just get a HX711, it's the simplest option and there's plenty of tutorials.

I mean, this is the schematic for the internals of the LM741 - and you'd need three of those, and it would still be inferior to an HX711.  https://i.sstatic.net/JmQjc.png

I agree with you I would not build an op amp from scratch-I already have a few lm358's-what I had in mind it could be done with a few transistors to amplify the mill volts output by the load sensor and use a simple circuit to convert them to useful voltages. It just seemed like you could make simple circuit from 20 components maximum.


text:
Logging without IDE
Is there a way to log events on Arduino when developing using C / AVR toolchain, and not the Arduino IDE? Working on Ubuntu.

Do you want your host system to record stuff received from an Arduino?  Or do you want an Arduino to record data?  Either way, the answer is yes, it can be done.

First one, I would like to see on my host what Arduino is doing.

The IDE uses a plain serial console to communicate with the Arduino.  You can use any serial console application you like.

On Ubuntu, I usually simply do
stty -F /dev/ttyACM0 raw 9600
cat /dev/ttyACM0 > the.log.file

Replace 9600 with your baud rate of choice.

Ha, neato. No character encoding mangling woes?

@user400344: The command is encoding agnostic: it moves the data from the serial port to the file as a byte stream, not a character stream. It could well be binary data for that matter.

Thanks, it will replace my terrible hack completely. Do you use something similarly simplistic to send data to your MCUs?

@user400344: No, I use text-based protocols, like in this command line interpreter, and type the stuff directly at the keyboard, usually through screen. You could cat the.data.to.send > /dev/ttyACM0 but, since the Arduino resets when you open the port, your sketch will miss the beginning of the file. You can avoid this auto-reset feature by putting a cap between RESET and 5V.

pretty neat. what value should I use for the cap?

I just use tip, I never liked screen

@user400344: 10 µF is recommended by the ArduinoISP tutorial, 1 µF always worked for me.

Thanks. I have looked at microbox which is similar to your interpreter. I like the clarity of your str-fu better, though. +1

Any of these are straightforward: python (serial library) or processing (same type of user interface, will happily build portable java programs for linux/win/mac). I use an awful perl script for logging stuff, can't recommend it. If you don't prefer the two first options, have a look at IPC::Open2 or IPC::Open3 - I use a bidirectional connection so I can send stuff, but I rely on 'tip' to do the serial connection stuff. If I wanted to log more than a few things, I would probably use python, which is much easier to read (later), and it will require a small fraction of the memory a fullblown java applet.


text:
The L LED Keeps Itself On
I am using a Arduino Uno 3 for line follower robot. However when I power the Arduino Uno, the L led is turned on and is never turned off. After a bit of searching I found out that the L LED is connected to pin 13. So I set the pin 13 to low but still the led is on. Is there a problem with the arduino? Or there's something that I am unaware about? (Amongst a lot of other things that I don't know.)

You need to tell us more about your line follower robot.  Specifically, where to find the schematic and code.  The way you worded your question is similar to asking: "Where is the headlight switch in my car?"

same problem here please cousld any one help!!
i used arduino uno its L led is not turning off it used to turn of but now no it is not it stays on .and blink code works but i am trying to make balancing robot but no it doesnt work i started uploading code for it this morning then after 3 hours i dont know how it worked for about 30 mins i was tuning the pid values while that 30 mins also the led was on though.but after that 30 mins i am trying but it is not working.Please help!

This is a “feature” introduced in the revision 3 of the Uno board. Up to
Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ
resistor. On Rev 3, the same LED+resistor combination is driven by pin
13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e.
INPUT mode, the default mode when the program starts), the input of
the op-amp is floating. The voltage at this input (and thus at the
output) is not controlled and depends only on the parasitic conductances
and on leakage currents.
If you want to turn the LED off, you not only need to write LOW to it,
you also (and most importantly) should set the pin to OUTPUT.

Now first check IC on your arduino UNO. if it is atmega328p, set the board to arduino nano in the software and set the processor th atmega328p. that makes it work.  :)

Its possible its the Power LED you are looking at - that will always be on.
Simplest test is to load up the Blink Example that's included in the Arduino IDE - and the LED should blink once a second. That will show you if your Pin13 LED is working ok.

The power LED is the green one, and the L led is the yellow one. I am looking at the yellow one

I guess the arduino is burnt cus it happens with me in the same way. The usb port of my PC is writing device not recognize, and the atmega328p on the arduino temperature is getting high. To save my time I bought another new one I think that should help.

An LED lights up when in forward bias.  That is, when the voltage on the anode is greater then that on the cathode.  If the anode is connected to an Arduino GPIO pin (and the cathode is connected to ground and an appropriate limiting resistor is used), the LED will light up when the pin has positive voltage.  This is when it is set to 1 in the code.  If the cathode is connected to an Arduino GPIO pin (and the anode is connected to positive voltage and an appropriate limiting resistor is used), the LED will light up when the pin has zero voltage. This is when it is set to 0 in the code.

authors: Сергей Романов


text:
build simple IR sensor with 220 ohm and 1000 ohm resistors
I am brand new to the arduino board and I am trying to build a simple IR proximity sensor. I bought a handful of emitters and detectors from amazon here:
https://www.amazon.com/gp/product/B01HGIQ8NG/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
I am about to pull my hair out and shoot my board with a 12 gauge shot gun if I don't figure this out soon. Can someone point me to a good SIMPLE tutorial that uses ONE emitter and ONE detector and ONE LED. All i can find are a bunch of complex circuits with multiple sets of sensors or a buzzer or whatever else and anything that is as simple as that has no information on schematic or code. Can someone please post a tutorial link?

You will not get good result in an unshielded environment from a simple setup.  To do well, you need either an external lock-in amplified which does synchronous analog detection of a pulsed signal, or to take reading with the ADC and implement a lock-in in software.

You could always start out attempting a simple IR detector circuit.
Google Arduino IR detector brings up several tutorials, such as this one from the Instructables website
You would have to change the buzzer in tutorial for an LED and resistor in series.


text:
Split a string as 2x16 for LCD
How do I split a string into two based on it's length to display on a 2x16 LCD?
I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?
Thanks

String::Substring does take a start and an end value. So you can do something like this:
String s1 = longtext.substring(0,15);
String s2 = longtext.substring(16,31);

That's what String::substring() is for. Simply take the first 16 characters and the characters from 16 to 32, and output them.

But,what about the rest of the string? I need 2 x 16 of the 32. Substring only provides one part right?

Use it as many times as you need in order to get all desired substrings.


text:
controlling LEDs, few pin outputs lots of LEDs
We need to control many leds, about 40 with arduino (UNO) and we need some remain turned on and other off at the same time. Muted or pinned vary constantly.
What should I use to do this, I have several Multiplexers CD4051 but with these I can just light a LED at a time.
I do some calculation and then need to turn LEDs 1,2,5,7 and need to be pinned to the following calculation. In the following calculation I need to turn leds 4, 5, 10, 12 pinned and need to follow. What I need is something like that
With the multiplexer I can turn the LEDs I need and with minimal delay and it seems they are apprehended while, but I want to know if there is another alternative to do so

Do they need to be lit constantly or do they need to appear lit constantly?

Well, I do some calculation and then need to turn leds 1,2,5,7
and need to be pinned to the following calculation.
In the following calculation I need to turn leds 4, 5, 10, 12
pinned and need to follow.
What I need is something like that

Alright, but that wasn't what the question was asking.

Well, I edit my question, it was bad explained

What my question was asking, rather.

Sorry, my english is not good. It would be perfect if they be lit constantly

Let us continue this discussion in chat.

The most common technique for doing this is called "multiplexing". You arrange the 40 LEDs into 8 "columns" and 5 "rows" with common anodes and cathodes, and then you switch the columns or rows on or off individually, activating only the LEDs you want lit for that column or row. If done quickly enough it appears to the human eye that the LEDs are always lit due to persistence of vision. Note that the physical display does not need to be a rectangle; this is simply the logical arrangement used in order to simplify the circuit.

(note that the cathode side of the above image is wrong; the cathode needs to be low when you want the LED to light)
(source)
A naive implementation with 8 columns and 5 rows would use 13 pins to connect them all. However, since you don't need more than one column at a time what you can do is use a 74HC138/238 to use 3 inputs to control which of the 8 columns you want to activate. This drops the number of required pins to 8, which is low enough for anything larger than a ATtinyX5. Use of a 74HC595 for the 8 pins further drops the required MCU pins to 3, which is low enough for even a ATtiny4/5/9/10, but the timing is harder to get right due to the shift register.

Check out NeoPixels. Make sure to check out the datasheet, as a single Arduino Uno might not be able to provide the required current.


text:
Complete Bread board arduino
I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

There are many usb to serial converter available on the market but can I make my own?

Yes, but if you need to ask how then you're not ready to undertake the task.

One more thing is there any other way burn program from arduino ide to microcontroller via usb on bread board without having the arduino board.

Yes. The IDE doesn't care how you connect to the MCU, only that it has the appropriate bootloader for the programming method.

Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

ArduinoISP will let you use an existing Arduino as an AVR ISP programmer. ISP does not require a bootloader, nor does it require a serial (UART) connection.

yea thank you. what is the issue of designing own usb to serial converter ;

Laying out a USB device needs knowledge and a bit of experience. It's not something for a novice.


text:
Light leds on this board one at a time
I am playing around with this Tinycircuits 16 LED board and I can figure out how to persistently light two LEDs at the same time. The page comes with an example that i can modify but I can only do 1 at a time
How do I light more than one LED at a time?
/*
TinyDuino Edge LED Demo

April 9 2014, by Ben Rose

This example code is in the public domain.

http://www.tiny-circuits.com

*/

void setup()
{
  LedOn(0);//Pass a zero to turn all LEDs off
}

void loop()
{
  for(int i=1;i<16;i++){
    LedOn(i);
    delay(20);
  };
  for(int i=16;i>1;i--){
    LedOn(i);
    delay(20);
  };
}

void LedOn(int ledNum)
{
  for(int i=5;i<10;i++){
    pinMode(i, INPUT);
    digitalWrite(i, LOW);
  };
  if(ledNum<1 || ledNum>16) return;
  char highpin[16]={5,6,5,7,6,7,6,8,5,8,8,7,9,7,9,8};
  char lowpin[16]= {6,5,7,5,7,6,8,6,8,5,7,8,7,9,8,9};
  ledNum--;
  digitalWrite(highpin[ledNum],HIGH);
  digitalWrite(lowpin[ledNum],LOW);
  pinMode(highpin[ledNum],OUTPUT);
  pinMode(lowpin[ledNum],OUTPUT);
}

Sorry I copied over the question with the paste of the code.

That is an interesting challenge. You should include the circuit diagram for this. It really helps understand the code.
.
There is excellent information on this technique to reduce number of pins here.
Cheers!


text:
Why is the nRF24L01 not working with Arduino Esplora?
I am working on a remote control car from an Arduino Esplora board and the Mega 2650 Board. My problem lies with the Esplora board as the nRF does not transmit like it is supposed to or does not even transmit at all.
I am using the pingpair_test.ino from the RF24 library to make sure the transceiver is working, and when I try to transmit on the serial monitor, I get the following output:
Configuration = t

STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0

RX_ADDR_P0-1 = 0x0000000000 0x0000000000

RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00

TX_ADDR = 0x0000000000

RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00

EN_AA = 0x00

EN_RXADDR = 0x00

RF_CH = 0x00

RF_SETUP = 0x00

CONFIG = 0x00

DYNPD/FEATURE = 0x00 0x00

Data Rate = 1MBPS

Model = nRF24L01

CRC Length = Disabled

PA Power = PA_MIN

Now sending length 4...No responses received. Are interrupts connected?

I have no idea what any of this means besides the interrupts part.
Even using interrupts(); the Arduino Esplora still refuses to send data. I am sure my wiring is correct because the status light on the nRF is on and I triple checked all of the SPI pins.
On the Esplora:

CE = 0
CSN = 1

On the Mega:

CE = 51
CSN = 50

I have a fritzing sketch here for those who want to see my wiring.

Bad wiring, check it three times and verify you are using the right pins. Another option is that your module is broken. Currently the library can't even detect the module (at all, like totally 0).

You may not be using the IRQ pin.   Mind posting your code so we can comment/troubleshoot?

@tr4nc3 - I have edited the question, and added a link to the actual pingpair.pde file. However, one thing that strikes me as odd is that the quoted output has a misspelling in recieved. However, the actual code line does not... How is that possible?

Uhh, also update your library it's ancient, either from the IDE of from https://tmrh20.github.io/RF24/.

@Greenonline Yeah I had to manually type the output because copy-paste wasn't working. Idk why.

As for the module being broken it isn't because I tried it on another board. And I repeatedly checked my wiring so I am 99.9% sure it's right.

This is really a comment, not an answer. With a bit more reputation, you will be able to post comments. For the moment I've added the comment for you, and I'm going to delete this answer. Thanks for your understanding and cooperation!

How much voltage are you supplying to the nRF24? It must be 3.3v.

Funny you should ask, I have been playing with nRF24 for a while, and was thinking of trying out my Esplora. There are however a few problems, which have postponed this (read: can't be arsed).

Pins. You need access to the SPI pins + 2 other pins. On the code you linked to, it's 8 and 9. Which won't work on an Esplora: D9 is not broken out, and D8 is CARD_CS. Better leave that alone. Your best bet would be to use the ICSP header and the two orange TinkerKit pins, D11 & D3.

[UPDATE] Also, the RF24 library uses D2 for IRQ, which is going to be slightly inconvenient on an Esplora, as this pin isn't broken out either. TMRh20 doesn't use an IRQ pin. Neither does Mirf.

As you can see, the Esplora is on 5V, which could give the nRF24 module a headache. You'll have to step that down to 3.3. Way too much work for me, but then again I'm lazy.
If you're planning on using the screen, the ICSP header is kind of in an awkward place. I've tried fitting regular cables under the screen, and all I've got for my pains was a big dose of what the heck.
Stand-alone power. If you're planning to use the Esplora as a standalone, you'll need a battery and a voltage stepper. So in the end, you could use the voltage of the battery for the nRF24 module, and the 5V output from the stepper for the Esplora. More work, grrr.

Looking at your output either you have a wrong wiring or, more probably, you need a capacitor between the nRF24 positive and negative pins: anything between 10uF and 100uF will do.

authors: توفيق الخولاني


text:
Sets of Ultrasonic frequencies using arduino uno
Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in  the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

I find a shotgun or a cat works best.  The latter is greener, but the former is oh so much more fun ;)

There are three parts to this project, one of which you asked:

I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the void setup{} part of your code, and (if you don't want to do anything else), leave the void loop() {} empty. You might want to generate an audible tone for a short period first, to show that it is working.

You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.
The circuit is pretty trivial. Google piezo arduino

Efficacy:

From https://en.wikipedia.org/wiki/Electronic_pest_control#Effects_on_rodents

Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.

You can specify a frequency up to 8mhz. - that's quite low, right? (Just kidding). I am skeptical that you would reach 8 MHz because the library toggles the pin in an ISR, and an ISR would have an overhead of a couple of microseconds. I would guess that 250 kHz to 500 kHz would be the theoretical maximum. Of course, this is a lot more than the 40 kHz that the OP wants.

You could and should maybe use a lot of transistors, and that might be whit you circuit and set the MHz overload higher then expected.

What library on arduino should i use?

You don't need a library. Tone() is built into the core.  There are some example sketches that come with the environment - just click File -> Digital -> toneMultiple. Note that this example plays different tones on different speakers (connected to different pins); for your code, put one 8-ohm speaker between pin 6 and ground, then change the first parameter of the tone() to 6 for all of them.

Is it possible to create an ultrasonic frequency by simply using it?  And can i used 45678Hz as my desired frequency?

"ultrasonic" is a function of our ears, an Arduino doesn't care if we can hear it or not. tone(pin_with_piezo,45678);

I connected the output to the ultrasonic transmitter but its not working. here is the transmitter specification that i used (http://www.farnell.com/datasheets/1498178.pdf) and the circuit diagram (https://www.google.com.ph/search?q=ultrasonic+circuit&espv=2&biw=1366&bih=643&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjoivap6-fJAhUK-2MKHdFeAFwQ_AUIBigB#tbm=isch&q=ultrasonic+transmitter+circuit+diagram&imgrc=fLTfT6_BQfBMyM%3A). can anyone help me regarding this problem?

Another answer to generating ultrasonic frequencies is to ditch the Arduino altogether - use a 555 timer circuit (for lower range frequency, probably up to low mHz), or a resonator. A quick search found a 2.4 gHz resonator for less than an Arduino. 555 timers can be tuned, resonators cannot. I think you could build a 555 square-wave generator for about $1-$2.

Hi, how can I strengthen the ultrasonic frequency produced by the arduino ic's?

This should really be a separate question, but: louder sounds can be made with higher voltage (up to the voltage supported by your piezo, or it will blow), using a higher voltage piezo, or one with a frequency response more suited to your frequency. If you want to use a voltage higher than the Arduino can handle, use a transistor as a switch (google).


text:
Digital pin input stays high after receiving a high signal
I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
int thermPin = A5;
int relayPin = 9;
int upButton = 10;
int downButton = 11;
int rawVoltage;
float mv;
float desiredTemp = 20.5;
float currentTemp = 20;
long newSetTime = millis();
long oldSetTime = newSetTime;
long newUpPushTime = millis();
long newDownPushTime = millis();
long oldUpPushTime = millis();
long oldDownPushTime = millis();
int mainDelay = 600;
int flashDelay = 600;
boolean isSetting = true;

void drawCurrentTemp(){
  lcd.setCursor(0, 1);
  lcd.print(currentTemp);
}

void drawDesiredTemp(){
  lcd.setCursor(12, 1);
  lcd.print(desiredTemp);
}

void drawMainScreen(){
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("TEMP");
  lcd.setCursor(12, 0);
  lcd.print("SET");
  drawCurrentTemp();
  drawDesiredTemp();
}
String setString = "SET";
void flashSet(){
  if(newSetTime - oldSetTime > flashDelay) {
    if(setString == "SET"){
      setString = "   ";
    }else{
      setString = "SET";
    }
    lcd.setCursor(12, 0);
    lcd.print(setString);
    oldSetTime = millis();
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(relayPin, OUTPUT);
  pinMode(upButton, INPUT);
  pinMode(downButton, INPUT);
  drawMainScreen();
}

void checkInput(){
  if(digitalRead(upButton) == HIGH){
    newUpPushTime = millis();
  } else {
    oldUpPushTime = millis();
  }
  if(digitalRead(downButton) == HIGH){
    newDownPushTime = millis();
  } else {
    oldDownPushTime = millis();
  }
  long upButtonTimePushed = newUpPushTime - oldUpPushTime;
  long downButtonTimePushed = newDownPushTime - oldDownPushTime;
  if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
    oldDownPushTime = millis();
    oldUpPushTime = millis();
    if(!isSetting){
      isSetting = true;
    } else {
      isSetting = false;
      drawMainScreen();
    }
  }
  if(isSetting){
    if(digitalRead(upButton) == HIGH) {
      desiredTemp +=0.5;
    } else if(digitalRead(downButton) == HIGH) {
      desiredTemp -=0.5;
    }
    drawDesiredTemp();
  }
}

void loop() {
  newSetTime = millis();
  if(isSetting) {
    flashSet();
  }
  checkInput();
  Serial.println(digitalRead(upButton));
}

Could it be because you don't have a pulldown / pullup resistor to force the input into a known state when there is no "signal"...?  Show your circuit.

yes :) I just found out about the pullup resistors and how exactly the INPUT works its all fixed now thanks :) i just made them pinMode(pin, INPUT_PULLUP);

I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.
When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.
So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.
As you mentioned using the code:
pinMode(PIN, INPUT_PULLUP);

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:
pinMode(PIN, INPUT);
digitalWrite(PIN, HIGH);

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.
Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.

Comment by Glen Cashen turned into an answer:
I just found out about the pullup resistors and how exactly the INPUT works it's all fixed now thanks :)
I just made them:
 pinMode(pin, INPUT_PULLUP);


text:
avrdude: stk500v2_getsync(): timeout communicating with programmer error
When I try to upload I get this error. I cannot upload the program into my Arduino Mega ADK board. I tried putting the drivers agiain too, but it does not work.
avrdude: stk500v2_getsync(): timeout communicating with programmer

Is it the problem with the hardware or the system?
Please help me. Thank you :)

See Have I bricked my Arduino Uno? Problems with uploading to board and What happens when code is uploaded using the bootloader?. I'm going to close this question. Thanks for your understanding and cooperation!

What @dda says in his answer are good points.
Removing the board USB for a few seconds, then re-plugging and re-selecting the COM port in the IDE usually fixes it.  Sometimes when you un-plug and re-plug the board it changes COM ports.
Also if you have a short-circuit wired to your arduino sometimes it becomes non-responsive in this manner.

I get this problem sometimes with some of my boards. I usually solve the problem following these steps:

Set the compiler on debug/verbose mode to see what's happening
Launch compilation/upload
When the compile phase is done, and the upload process is about to start, press the reset button on the board

Usually that takes care of the problem.


text:
Background processes - Arduino Mega and SeeedStudio CAN shield
I am attempting to interface an Arduino Mega 2560 with a system of four Black Jaguar motor controllers connected in CAN. I'm using the CAN shield from SeeedStudios to accomplish this.
The way Jaguars in CAN mode are configured, you must send a message every 100 ms to the network to keep the link active. However, I'm also getting input from Serial to another Arduino as well as sending other commands to the Jaguars, but not regularly enough to specifically time it out.
Is it possible to have the link message sent asynchronously in the background while I perform other code? I have looked into timers and interrupts, however I am unsure if this would truly solve the issue considering I have other processes that take more than 100 ms to complete.
Here's my loop statement:
loop() {
  CAN.sendMsgBuf(HEARTBEAT,1,0,volModeEnable); //HEARTBEAT keeps CAN link active
  setVoltage(3,.5); //Sets voltage of Motor by percent
  setVoltage(4,.5);
  setVoltage(6,.5);
  setVoltage(8,.5);
  //GrabFromSerial(); Takes longer than 100ms
  //Control Statement for Additional Commands goes here... (also necessary to be > 100ms)
}

Just curious why does it take you more than 100ms to read the serial port?

Im using this library: https://github.com/madsci1016/Arduino-EasyTransfer to save me the trouble of writing my own serial protocol.   However i cant always garauntee it's time to execute because of the other arduinos timing.

I havnt looked at the library but perhaps it would be more simple to write your own protocol. Then you can use methods such as serial.available() that will tell you when data ia ready to be received without blocking the execution of your program

I see several options:

Change your code to achieve lower delays on the other functions
Use interrupts at a set frequency to trigger the sending (and maybe the automatic transmission trigger pins, see MCP2515 datasheet, depending on pin use & schematic of your specific shield)
Use a basic scheduler/rtos

It is hard to tell what is going on without the rest of your code, if it is a good idea to try to achieve faster functions.
I am not 100% sure the CAN-lib would will work well in the context of an interrupt.


text:
A question about the possible limits of an Arduino Uno
I've searched the web but could not find a straightforward answer to my query.
I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.
Anyway, I have a single Arduino. It is operating the following:
An LCD display,
a 4 button operation panel I made using an LS148 ic,
an L293 operating 2 small motors,
a servo,
a dark sensor,
a temperature sensor,
and it also does serial communication.
Everything is working great, but slow (or so it appears to me).
If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.
When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?
I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.
I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.
Thanks for your advice.

Did you mean a "74LS148"?

Yes I did. xxxx

A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.
For instance, take the LCD code.  Commands have to be sent at the right speed with the proper delays in there for things to happen.  LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.
Nothing else can happen while there's a delay() running.
Many other things will introduce their own delays.  Put them all together and you have a slow system.
No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.
There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.
For a start there is the millis() function which tells you the time.  Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.
It's like boiling an egg.  Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?
It's the same with Arduino programming.  Note the time, then check that time against the current time to see if the required time has passed.
Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.
There are also hardware timers.  These allow you to run small snippets of code at regular periods.  Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.
There are two key phrases to take away here:

Non-blocking.  That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.
Asynchronous programming.  This is using things like timers to make things happen "outside" your main loop.

So you are saying that the list of components and circuits have no effect and my problem most likely is in the code?

More than likely, yes.  External components don't affect the speed of the chip, only how you program it can do that.

The problem with most of the Arduino libraries is that they are sort of ok at doing one task, but they do it inefficiently and monopolize the whole device.
So when one tries to do a real system, problems like this one are quite common.
One solution is to use more units, each with a specific purpose. After all they are fairly cheap. Alternatively, get rid of the Arduino code base and just treat it as normal AVR, using for example FreeRTOS.

Another good choice would be to work with Cosa as the core instead of Arduino.  If you switch to UECIDE instead of the Arduino IDE you can switch between Arduino and Cosa as the core at will.


text:
How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC?
I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?
I already tried every thing that I found on the internet but it just doesn't work.
I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...
I tested it on the browser directly and the value shows up, so I think that the server side is all right.
Here is my Arduino code:
#include <Arduino.h>
#include <SoftwareSerial.h>
#include "WiFly.h"
#include "HTTPClient.h"

#define SSID      "mySSID"
#define KEY       "myKEY"
#define AUTH      WIFLY_AUTH_WPA2_PSK
#define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

// Pins' connection
// Arduino       WiFly
//  2    <---->    TX
//  3    <---->    RX
SoftwareSerial uart(10, 11);
WiFly wifly(uart);
HTTPClient http;
char get;

void setup() {
  Serial.begin(9600);
  Serial.println("------- WIFLY HTTP --------");
  uart.begin(9600); // WiFly UART Baud Rate: 9600
  // Wait WiFly to init
  //  delay(3000);

  // check if WiFly is associated with AP(SSID)
  if (!wifly.isAssociated(SSID)) {
    while (!wifly.join(SSID, KEY, AUTH)) {
      Serial.println("Failed to join " SSID);
      Serial.println("Wait 0.1 second and try again...");
      delay(100);
    }
    wifly.save(); // save configuration,
  }
  Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
  }
  if (wifly.commandMode()) {
    Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
  }
}

void loop() {
  int c;
  while (wifly.available()) {
    c = wifly.read();
    if (c > 0) {
      Serial.write((char)c);
    }
  }
  while (Serial.available()) {
    c = Serial.read();
    if (c >= 0) {
      wifly.write((char)c);
    }
  }
}

And here is my PHP code:
<? php
include("./connection/database_connect.php");
include("./top_table.php");

if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
  $id = $_SESSION["ID"];
  $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
  $consult = mysqli_query($connect, $sql);
  $result = mysqli_num_rows($consult);
  if (($result == 1)) {
    $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
    $temp = $person_data["temp"];
    header("HTTP/1.1" . " " . 200 . "OK");
    header("Content-Type: text/html; charset=UTF-8");
    header("Content-Length: 1112");
    header("Connection: close");
    header("/r/n");
    echo $temp;
  } else {
    //se user dosen't exist on data base
    header("Location: http://192.168.1.80/xampp/training/login.php");
    exit;
  }
} else {
  header("Location: http://192.168.1.80/xampp/training/login.php");
  exit;
}
?>

Step 1: confirm if the request is reaching the Apache server.

Sorry the delay but I just saw it now...
Yes the request is reaching the server. I tried with a simpler code just to be sure and the server sends a response, but not what I want.
It seems that the $_GET['temp'] is not set...

php/?temp - That looks "iffy" to me.  Should that / be in there?

I think so, just a while ago I spoted an error in that line I had "php/?$temp"  in there and solved part of my problem. It seems like the problem is that the $_SESSION can't be reached. And besides that my web page on the browser dosen't react

$_SESSION either needs cookies or a PHPSESSID=.... parameter, neither of which you will likely have.

hum... that might be an issue, I'm only logging in an user in my browser and start the session in "include('./top_table.php'), maybe it isn't enough.
I thought that with the user logged in I could user his $_SESSION but it seems not...
Does PHPSESSID changes ever new session? if yes i don't think i can use it in Arduino code as a variable.
what should i do? register arduino along with the info of the person/house? With that i might be able to acess the person ID and reach out "temp"

The PHPSESSID is a unique key that identifies the session.  It is allocated by PHP when the session is opened and must be provided back to PHP with every request to be able to access the session.  What you could do is perform a 2-stage login action, where you first go to a "login" page which returns your session ID, and then you make your normal (and all subsequent) request(s) including the session ID.

Filipe I need your help. Can you help me out from this! I need to store voltage sensor data from arduino mega using shield in local server. Please contact me at sjisylhet.partha@outlook.com
thanks for your time.

You should forget about the $_SESSION["ID"]; on PHP side, because you are working stateless without any session!
You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange
$sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

with
$sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

assuming that perfil.id is only an integer - if it is a string, then add "'".

Yes you are right!
Meanwhile i finished this project.
The problem was with the Wi-Fi shield that I was using. The Http request wasn't in a right format.


text:
Reading from EEPROM and combining
I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error
error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

void loop()
{
  const char* eTest1 = EEPROM.read(1);
  const char* eTest2 = EEPROM.read(2);
  const char* eTest3 = EEPROM.read(3);

  char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
  bluetooth.write(combinedVal);
}

btw: for a C string (char array terminated with 0), the write function is same as print()

You cannot use the + operator for that.
However, since EEPROM.read only returns one byte and not a string, you can do a much easier implementation:
void loop()
{
  char result[] = "1:2:3";
  for (int item = 0; item < 3; item++)
  {
    result[item * 2] = EEPROM.read(1 + item);
  }
}

This first create a string "1:2:3", where the digits are overwritten in the for loop by that item. Note that the digits in the string do not matter, it's just some free 'comment', it also should work when using "x:x:x".

Ok thats great it trys to combined them but comes up with the following error                                 warning: invalid conversion from 'uint8_t {aka unsigned char}' to 'const char*' [-fpermissive]
const char* eTest1 = EEPROM.read(1);
^

@Rickstar I made a better implementation, since EEPROM.read always returns exactly one byte (character).

@Rickstar EEPROM.read() returns one byte, not a pointer to string.

Thanks @MichelKeijzers

You're welcome.


text:
Potentiometer reading out letters
My potentiometer reads out t's or u's in my serial.
I believe that my potentiometer is wired correctly.
What am I missing?
Here is my code:
#include <VarSpeedServo.h>

VarSpeedServo servo;
const byte buttonLeft = 2;
const byte buttonRight = 3;
const int led = 7;
const int potentioPin = A0;
int potentioVal = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(11);

  // PIN MODES
  pinMode(buttonLeft, INPUT);
  pinMode(buttonRight, INPUT);
  pinMode(led, OUTPUT);

  // INTERRUPT
  attachInterrupt(digitalPinToInterrupt(buttonLeft), turnServo, FALLING);
}

void loop() {
  int stateBtnLeft = digitalRead(buttonLeft);
  int stateBtnRight = digitalRead(buttonRight);

  if(stateBtnLeft == 0 && stateBtnRight == 0){
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
}

void turnServo(){
  Serial.println("Button was pushed");
  potentioVal = analogRead(0);
  Serial.write("Servo moving with speed ");
  Serial.write(potentioVal);
  Serial.println("");
  //servo.write(180, potentioVal, true);
  //Serial.write("Reached position of motor");
  //lightLed();
}

void lightLed(){
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}

You need to use Serial.print instead of Serial.write.

write() is a function for binary data. I you want to print the number as text, use print() or println().
Serial.println(potentioVal);


text:
Why are some of my GSM modules not taking commands?
I posted a couple weeks ago about having a GSM error. I moved past it and the code seemed to be working on my GSM module (I think a SIMCOM). But then I needed to create some more systems and out of a total of 8 GSM modules, my code and setup only work on two of them - despite the fact that they should be identical and from the same supplier.
The following code (thanks to this genius post) works without error to send and receive SMS on two of the boards:
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900 = SoftwareSerial(2,3);

void setup() {
  Serial.begin(19200);
  initializeGSM();
}

void initializeGSM() {
  SIM900.begin(19200);
  Serial.println("Turned on");
  SIM900.print("ATEO\r");
  Response();
  SIM900.print("AT\r");
  delay(1000);
  Response();
  SIM900.println("AT+CMGF=1\r");  // set SMS mode to text
  Response();
  delay(1000);
  SIM900.println("AT+CNMI=1,2,0,0,0\r");
  delay(100);
  Response();
  delay(5000);  // give time to log on to network.
  Serial.println("Ready...");
}

void Response() {
  int count = 0;
  delay(1000);
  Serial.println(SIM900.available());
  while(1) {
    if(SIM900.available()) {
      char data =SIM900.read();
      if(data == 'K'){Serial.println("OK");break;}
      if(data == 'R'){Serial.println("GSM Not Working");break;}
    }
    count++;
    if(count == 100){Serial.println("GSM not Found");break;}
  }
}

void loop() {
  RecSMS();
  delay(2000);
}

void RecSMS(){...}

So again, the above code works to set up the module on 2 modules. On the other 6, it simply hangs during the Response() call. SIM900.available() returns 0 and then says "GSM Not Found." So I tried to initialize the TX pin during setup as:
digitalWrite(2, LOW);

Which then gives me a promising SIM900.available() value of about 63, which corresponds to what a confirmation would be. However, when I print the "data" variable containing the byte read off the GSM module/SIM card, I get a couple bits of garbage like the following output:

Has anyone experienced this problem and knows a way to properly initialize the GSM module?

GSM module running at a different baud rate?

Is there a way to determine which baud rate it's running at? Or reset it?

Experiment by trying different common "standard" baud rates - if you find that a different one works then that's your problem. If not, then it's not.

I tried all of the baud rates from 2400-115200 and they all produced similar outputs. I also tried changing the jumper pin on the GSM module to change the TX/RX pins but that did not work either.

In your initialize-func after sending the AT+CMGF=1 you have the Response() before the delay(). I wonder if that matters.

It may well be worth to actually print the error codes instead of only check if there is an error. You can even try manually sending AT commands, to verify that they work. When I worked with GSM units, I found that they are extremely picky on the amount of power they require in peaks. Be sure your supply is capable and add a capacitor that can take a very short 2A burst.

I am owner of this blog whose link you shared, so first of all, I am felling happy that you got something out of it. Now secondly, this code you got from my post is incomplete.
You need to buy that one in order to get the complete code. The code I designed is using AT commands but the above code which you have mixed with your own code is using the Arduino library that's why it's not giving the correct results.
So, either use the complete code from my website or use the Arduino library code only because it has the commands for checking the response, you don't need to use my code to get the response.

authors: المهندس اليماني


text:
No Data Received on Serial Port & Unable to DFU Reset. Advice?
Having a problem running my original code that I tested last week, which worked on multiple days last week.
I tried to do a DFU reset and update the BootLoader, but it didn't work. I checked the baudrate and board selections in the Tools tab, but those were fine.
I didn't change anything in the code, I checked the wires on the hardware setup (nothing looks loose).
Thought it could be an error with the USB cable, changed the USB cable to a different one, still same error.
Also - using a Mac. But the same issue arose on the Windows PC. Did not try to reset using the Windows computer, but reset issue has more to do with the other hardware?
Checked the serial port - and it's selected to right one.

Maybe you should choose the right serial port.

True, forgot to mention that. I did check that though, I only have one serial port (have a driver to be able to get serial data on the Mac - and that has worked). It's selected to the only valid serial port.

Clarification - to do a DFU reset - you have to make sure the DFU and ground pins are connected with a jumper wire. You click the reset button - and try to update the bootloader?

Well, the port you have selected is (the hint is in the name) a bluetooth port, not a USB port.

Whoops - okay thanks. Don't know much about UART - that specifies serial communication? The two devices use SPI and I2C.

It seems to be working. Thanks.

Step Zero - check that the port selected works.
Step Next -  if you still get the error, try the DFU reset options and follow the steps outlined in the link below.
https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/using-the-bootloader

It's OK to accept your own answer as the solution to the problem.


text:
A confusing condition statements
I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a kitchen timer.
In that code I found a statement
currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;
I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it.
What does this statement mean?

it is if (currentMode == MODE_IDLE) {currentMode = MODE_RUNNING;} else {currentMode = MODE_IDLE;}

http://www.tutorialspoint.com/ansi_c/ternary_operator_examples.htm

I think adding parenthesis makes it much more readable:
currentMode = (currentMode == MODE_IDLE) ? MODE_RUNNING : MODE_IDLE;

Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.
if you do not understand ternary operators, it can be re-written as:
if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

You should read up on the ternary operator.  It appears in several languages in various formats and can come in handy in a variety of situations.
In general terms the ternary operator is of the following form (as used in an assignment):
result = (booleanExpression) ? (value if true) : (value if false);

but you can use it in other contexts for example in a function call:
someFn(booleanExpression ? trueValue : falseValue);

does Internet need another ternary operator explanation?