text:
Sending Large Packets and Reassembling over Serial
I'm trying to send info of about 30-40kB over the Serial ports on an Arduino Due. But I'm running into a few problems.
First, before we get into the actual transfer over the Serial, I want to try storing 30000 Bytes into a char * array.
Also as a disclaimer, I've modified the SAM library's RingBuffer.h SERIAL_BUFFER_SIZE to 256 from 128.
void setup() {
  Serial.begin(115200);
int i,j=0, cksum=0;
int *test;
test = (int*)calloc(1,30000);
Serial.println("Starting...\n");

for(i=0;i<30000;i++){
  test[i]=i;
  cksum +=j;
  j++;
  if(j>255){j=0;}
}
Serial.print("cksum is: ");
Serial.println(cksum);
cksum = 0;
for(i=0;i<30000;i++){
  if(i<300){ //only print out the first 300 characters, otherwise it's hard to see anything
    Serial.print("[");
    Serial.print(test[i],HEX);
    Serial.print("]");
  }
  cksum+=(int)test[i];
}
Serial.print("\nNow cksum is: ");
Serial.println(cksum);
}

Obviously, since *test is a byte array, I'm only storing int8 into there - so from 0-255.
That means that the data received in *test increments from test[255]= 255 to test[256] = 0. The way around this would be to use some kind of itoa function to write out multiple bytes that represent the numbers being written (causing an overflow because it would no longer be an array for 30000 Bytes). But for these purposes is it ok to simply realize that this is happening and just write the bytes to the array.
Ok, so for part two, I want to do the same thing, but by writing to Serial2 from Serial3 and receiving all of the bytes:
void setup() {
  Serial.begin(115200);
  Serial2.begin(115200);
  Serial3.begin(115200);
int i,j=0;
double cksum=0;
char *buf;
Serial.println("Starting...\n");
buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }
 Serial.println(cksum);
 Serial.println("Reading from Serial2");
 Serial2.readBytes(buf,30000);
 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

What happens here is that I get a mismatch at byte 255. The increment (in hex) goes:
[254] = FE
[255] = 30
[256] = 31

But it should read:
[254] = FE
[255] = FF
[256] = 0

After reading some other forums, and the fine AVR Arduino post here, I feel like something is happening on the Serial interrupt level that I am not aware of. All of the data is properly transferred to the Serial and I am able to see all of the bytes in the correct order coming out of TX and into RX on my logic analyzer.
I've also experimented with different baud rates, but see no reason why a 84Mhz chip would not be able to handle a baud rate of 115200.
Has anyone else run into this? How do you handle these transfers of continuous data that is larger than the buffer? Is the only option here to run readBytes in SERIAL_BUFFER_SIZE increments until Serial is no longer available? Or can I still salvage using readBytes all in one go as I am trying to do?
I know this question has been asked in certain forms in other threads like here and here but they do not solve this particular problem I am experiencing, most likely because they are not Due specific.

I think you have a fundamental lack of understanding about how serial communications works.

You write 30,000 bytes of data out of a serial port, then read that data as it appears on the UART pins into a 256 byte buffer. Once you have sent all 30,000 bytes into that 256 byte buffer you then try and read 30,000 bytes out of that 256 byte buffer and wonder why it doesn't work right...?

Imagine you have a bucket with 30,000 marbles in it, and two cups that can hold 256 marbles each. You want to empty the bucket of marbles and then put all the marbles back in again. How do you do it without getting marbles all over the floor?

Yes, clearly the Arduino code does not handle this contingency properly as I would have hoped. It requires a rewrite of the stream function read().

No, it requires a rewriting of your understanding of serial communications.

I have done that, and lost a few marbles in the process. But it indeed does require a rewrite of stream. If you want to read any amount of continuous data that is larger than your buffer size, you need to include the specific uart driver for the chip and use the interrupt routine uart_is_rx_buf_full. In fact, this is how readBytes() should work in the first place, but it is mainly written for AVR chips.

Please refer to chapter 34 of the SAM3X8E datasheet to understand how the Serial characteristics work on this particular chipset.

The existing buffer does that job. It is up to you to then read from that buffer fast enough and at the right time.

If the existing buffer handles the rx_buf_full interrupt (which it does not if you read HardwareSerial.h and UARTClass.cpp), it simply sets up a ring buffer. If you think that this is actually how the Serial class already works, then please explain how the code I provided does not read from the buffer fast enough at 115200 and that the read does not come at the right time.

The heart of your problem is that you are writing 30000 bytes then reading 30000 bytes instead of reading 30000 bytes whilst writing 30000 bytes. You have to do both at once.

Can you please clarify where you are sending the data to? Are you sending it to the same device? Why? You already have it there.

Let me dissect your program and show you precisely what is going on and why your approach is completely wrong:
Your first step is to throw 30,000 bytes at the serial port. Those go via the TX ringbuffer, which is (as you have changed it for some reason) 256 bytes:
buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }

At this point 29744 bytes have left the hardware UART. 256 are still sat in the TX ringbuffer being sent out by the TX interrupt routine.  The first 256 bytes that were sent out were picked up by the RX interrupt routine and stored in the RX ringbuffer. The next 29488 bytes were discarded (they are now all over the carpet with your marbles).
 Serial.println(cksum);
 Serial.println("Reading from Serial2");

Now you try and read 30,000 bytes from the 256 byte RX ringbuffer. While you are doing that the remaining 256 bytes in the TX ringbuffer are being slowly sent out. You are now making some room in that RX ringbuffer since you are removing bytes from it, so some of the remaining 256 received bytes can now be stored in it. The first one of those happens to be 0x30.
 Serial2.readBytes(buf,30000);

Now you go and print out your array, which has only a tiny fraction of the 30,000 bytes you sent in it.
 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

The simple fact is, you are transmitting, en-masse, far more bytes than the Arduino's RX ringbuffer can hold. In order to receive more than the 256 bytes of the ringbuffer you have to read the bytes from that ringbuffer to make room for more to arrive. And since you are the one that is transmitting that means you have to do your receiving at the same time as the transmitting.
The only possible way that your arrangement of program could work would be if you increased the RX ringbuffer to greater than 30,000 bytes so it can store all the received bytes as you transmit them for you to then, afterwards, copy the contents of that ringbuffer into your own buffer.

After a lot more research, this is actually the way that the buffer should work (the way I had originally written it) according to the Atmel datasheet and Atmel ASF. There is a bug in the Arduino kernel, I have fixed Streamio it and it works now (as the original code) that you where you confuse the functioning of RingBuffer and how StreamIO works on an ARM chip. I will recommend this fix to Arduino.

int *test;
test = (int*)calloc(1,30000);

First, I would be testing if that calloc worked. 30000 bytes is a lot on any microprocessor. For example:
test = (int*)calloc(1,30000);
if (test == NULL)
  {
  Serial.println ("Insufficient memory.");
  exit (1);
  }

Second, can't you calculate the sumcheck on-the-fly?

for(i=0;i<30000;i++){
  test[i]=i;
  cksum +=j;
  j++;
  if(j>255){j=0;}
}

If you want to send a sumcheck at the end, calculate as you send each byte and then send it afterwards. That way you don't need the 30000 byte array.

Your technique of sending 30000 bytes and then trying to read them back is hoping that the 30000 bytes will be saved somewhere while you are writing and before you read. Where?

I've modified the SAM library's RingBuffer.h SERIAL_BUFFER_SIZE to 256 from 128.

Certainly not there. That now holds 128 bytes.
So you are expecting a buffer of 30000 bytes which you set up, plus another 30000 bytes somewhere to hold the data while you send it. Even on the Due you are using most of your available RAM for this exercise.

What are you really trying to do here?
http://xyproblem.info/

Well I've got two FIFOs here. When the read comes in, I get an interrupt and service it. We're talking milliseconds. I should be able to service the interrupt, grab the byte, service it and go into the next one.

Is it a problem in the streamio? Or is it the Arduino library over it?
All of this stuff is an extension of Streamio. Arduino is extending this class which is where HardwareSerial comes from. HardwareSerial uses a class inheritance to make its own reads and writes. So you are saying that the Due framework does not handle the serial buffer properly?

When the read comes in, I get an interrupt and service it. - yessss ... well your code doesn't have interrupts in it, so I assume you are talking about the Serial class interrupts. Certainly they service the interrupt, grab a byte, and put it somewhere. But they put it into the 128 byte buffer you have.

So you are saying that the Due framework does not handle the serial buffer properly? - no I'm not saying that. I am asking you why you want to send 30000 bytes from your Due to itself, when it would be a whole lot easier to cut the Serial processing out of it altogether.

Yes, this is just an exercise I'm using to get a handle on how the Arduino kernel is handling serial data. https://developer.mbed.org/cookbook/Serial-Interrupts

Oddly enough, an exercise to check how things might work in a larger situation, can fail in a simulation. For example, sending from HardwareSerial to SoftwareSerial on a single board. A better test would be to split the test between two Arduinos, where one sends, and the other receives. That is, after all, closer to what you will eventually do. As an analogy, try making up 1000 random numbers, and telling them to yourself (as a batch). You will probably have trouble doing that, but if you told them to another person they could repeat each number as they got it.

I have made this example work by modifying the Arduino kernel and Streamio. No need to send the data as a batch, but if you read chapter 34 of the Atmel SAM chip datasheet it explains what should be done to the UART, and the Arduino files did not handle it correctly.


text:
ESP8266 stops responding when isolated relay is connected to AC tubelight
I'm completely new to Arduino and do not have an electronics background.
I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.
I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.
I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html.

This is my code.
#include <SoftwareSerial.h>

#define DEBUG true
int relay = 8;
SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different
  pinMode(relay, OUTPUT);
  digitalWrite(relay, LOW);

  sendData("AT+RST\r\n", 2000, DEBUG); // reset module
  sendData("AT+CWMODE=3\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWJAP=\"xxxx\",\"xxx\"\r\n", 5000, DEBUG); // configure as access point

  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
}

void loop()
{
  if (esp8266.available()) // check if the esp is sending a message
  {

    if (esp8266.find("+IPD,"))
    {
      delay(1000);

      int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
      // the ASCII decimal value and 0 (the first decimal number) starts at 48

      if (esp8266.find("=="))
      {
        Serial.print("State : ");
        char c = esp8266.read();
        Serial.print(c);
        if (c == '1') {
          digitalWrite(relay, HIGH);
        }
        else {
          digitalWrite(relay, LOW);
        }
      }
      String webpage = "A";

      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; // append connection id
      closeCommand += "\r\n";

      sendData(closeCommand, 3000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  esp8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {

      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}

The above code works perfectly until I connect the tube light to the relay.
The power supply used in 9v 1A wall adapter.
The relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o03_s00.
The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.
I'm really struggling hard to proceed here. Any help or hint would be much appreciated.
Thanks in advance.

Finally I got this working using only ESP8266 and minor tweaks. I'll post the circuit here just in case if somebody is trying to do the same thing.
Please note that this was done as a POC and I'm not from an electronics background.

Kindly note the blue wire from the GPIO 01 to resistor and an LED. I had to do this because when the circuit is powered on a HIGH signal is sent from the GPIO and the relay is turned on. I think it is the default behaviour of ESP8266. To suppress this initial flow, I did this (There may be a better way to do this according to electronics experts).
Diode used is 1N4001 Diode
Decoupling capacitor is - 10nf/100V (0.01uf/100V) Box Capacitor - Polyester
Relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o05_s00
Transistor is bc547.
Before connecting the devices, I flashed nodemcu firmware to ESP8266 so that I can write code in Lua script. Refer any of these to flash the firmware -  https://www.youtube.com/watch?v=Gh_pgqjfeQc
https://www.youtube.com/watch?v=pp6O96B1-Jk
I used LuaLoader to transfer the following code to the ESP8266.
http://randomnerdtutorials.com/esp8266-web-server/
I'm posting my init.lua below.
init.lua
wifi.setmode(wifi.STATION)
wifi.sta.config("<ssid>","<password>")

cfg =
  {
    ip="192.168.1.101",
    netmask="255.255.255.0",
    gateway="192.1681.1"
  }
  wifi.sta.setip(cfg)

print(wifi.sta.getip())
led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
 gpio.write(led1, gpio.LOW)
 gpio.write(led1, gpio.LOW)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
print("receive")
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf.."<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
 Control Panel
";
        buf = buf.."
Tubelight <button>ON</button> <button>OFF</button>
";
        local _on,_off = "",""

print(wifi.sta.getip())
        if(_GET.pin == "ON1")then

              gpio.write(led1, gpio.HIGH);

        elseif(_GET.pin == "OFF1")then
              gpio.write(led1, gpio.LOW);
        elseif(_GET.pin == "ON2")then
              gpio.write(led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
              gpio.write(led2, gpio.LOW);
        end

        client:send("HTTP/1.1 200 OK\r\n");
        client:send("Content-type: text/html\r\n");
        client:send("Connection: close\r\n\r\n");
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

If everything is running, connect your phone or computer to the same wifi using "<ssid>","<password>" and access the IP 192.168.1.101 to see a webpage with one buttons "ON" and "OFF". Click on it an check whether it is working.

If you are doing what you have said you are doing then I think the answer is so obvious no one will ever see it.
You say you have a 9V 1A power supply.  Since you are powering the Arduino from this it is DC.  Is that correct?
You are connecting an "AC Tube light" to the relay (which supports 1A 12V DC).
If you are connecting an AC device to a DC supply then things probably do go wrong.
To test everything is working properly can you switch the AC light for a DC light?
I think you can get Relays with AC output and a DC Switching signal, but that will need a bit of research.
Hope that helps, if not comment and I'll try again.

"I think you can get Relays with AC output and a DC Switching signal" - This is what I'm doing. By the way I got it working with using only ESP8266. I'm not sure whether I can post that answer here as I don't use adruino.

@SherinMathew, sorry mate I had to check. :)

If you can get the circuit working without the relay, and you can get it working without the Arduino can you get the Arduino driving the relay (no esp) ?

Yes, I was able to drive the relay using Arduino. I was using a PIR sensor to switch on the same tubelight using Arduino and relay. That was my first experiment. Then I decided to control the same using my phone. That is when ESP8266 came into picture.

I think you might be drawing too much current because the parts work but not the whole.  When you ran the esp8266 test were you powering the 3v from the Arduino? Could you power the relay from a separate psu and use a transistor to let the Arduino switch it?

Thanks for the suggestions @Matt. I tried all those options. Finally used ESP8266 alone as I only wanted to prove that I can control AC using my phone. I didn't bother too much to make it work with Arduino and ESP8266.

I suspect that you've connected the relay wrong. I think that the LNP of the relay is supposed to be connected to D8 and the v+ to 5/3.3V and GND to GND....

Relay connection is correct. V+ of relay to 9v, GND of relay to GND and INP of relay to D8. As I mentioned in the question, it is working perfectly fine when the AC load is not connected.

I suppose it has something to do with the relay. I'm going to try with Solid state relay.

Noise more likely. Try optoisolating or decoupling (attach >100uF electrolytic capacitor to the power pins) the supply to the ESP.

source: Stack Exchange

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

sort: votes


text:
How to send volume +/- on Mac/OSX from Leonardo
I saw this answer but I can't find the analog for Mac.
I've tried cycling thru keycodes from 0x01 thru maybe 0x500, and I went thru ascii a few times, also found brightness up/down, and F11, F12, but they get pressed with fn key by default which makes them do operations other than vol +/-.

What makes you think that the upvoted answer in the other question doesn't apply to Macs?

@IgnacioVazquez-Abrams 1) I tried those codes 2) I can't find xev for mac.

Could you just untick the "Use all F1, F2, …" in System Preferences -> Keyboard?

Just wondering if that would be an option and if doing so would create the desired outcome.

I will try this out!

it was already unticked, changing it made no difference :(

Unfortunately, Fn is hardware and it is handled internally by the keyboard to do something hardware-based without sending any code. So the short answer is: you can't simulate Fn key with arduino.
What I think of as a solution is:

Create a program on your Mac that can listen for keyboard scan codes to do vol +/- or any other function.
Send a custom scan code from Arduino to your Mac ( a scan code that isn't part of the standard scan codes ).
When your listening program receives that code, it should do Vol +/- (or anything else )...

in my case there is no listening program, the leonardo equiv. board (irduino) is acting as a keyboard.

Oh sorry I may have misunderstood--- you mean to say create a custom mapping on the mac with keys I can send, have those alter volume, and run it along-side using the leonardo? This might work; I'm hoping to find a way to just send the keycode. I have a 3rd party USB keyboard that sends vol +/- just fine so I know keyboards can do this somehow.

I don't actually own a Mac, so my solutions are somehow limited, however, check out this page: http://lists.apple.com/archives/usb/2011/Aug/msg00020.html

It does say  : " Usage 233 (0xe9)  [volume up], Usage 234 (0xea)         [volume down]"

You might want to try these codes and see if that does something ...

Those third-party keyboards are using some sort of composite HID ( not only HID keyboard but also HID Consumer Device ).

thank you! it did not end up working, 0xe9 sends a "9" and 0xea sends "0"

Yes, as I thought, when your arduino acts like a HID Consumer Device, and you send 0xe9 or 0xea that will trigger vol+/- ..

but as long as it is  just a HID keyboard that won't work.

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


text:
Using Keyboard library for ISO-UK layout
I am creating a keyboard and the PC I use it with is configured for UK so the keyboard layout it expects is this

I've highlighted the ISO-UK vs ANSI-US differences but the only key I am having real problems with is the backslash key.
My physical layout is actually this (ortholinear "Planck") but it's essentially the same except with two logical layers and variation in positioning.

The above is a fully functional UK-layout keyboard with the exception of the "\" key.
The sketch I am using is too large and distracting to post here but the following test sketch
#include "Keyboard.h"

byte keylist[] = { '`', '2', '3', '\'', '#', '\\' };

void setup() {
  Keyboard.begin();
  delay(1000);

  // unshifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(keylist[i]);      delay(100);
    Keyboard.release(keylist[i]);    delay(100);
  }

  Keyboard.press(KEY_RETURN);
  Keyboard.releaseAll();

  // shifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press(keylist[i]);
    delay(100);
    Keyboard.releaseAll();
    delay(100);
  }
}

void loop() {
  delay(1000);
}

Creates this output (in a Notepad window)
`23'£#
¬"£@£~

I did try switching focus to a keyboard diagnostic tool - KeyHitter by Elite Keyboards which showed different results
12:31.0675 ` (0xDF, BIOS 0x29) DOWN
12:31.0771 ` (0xDF, BIOS 0x29) UP -> 100ms
12:32.0772 2 (0x32, BIOS 0x03) DOWN
12:32.0871 2 (0x32, BIOS 0x03) UP -> 100ms
12:33.0872 3 (0x33, BIOS 0x04) DOWN
12:33.0972 3 (0x33, BIOS 0x04) UP -> 100ms
12:34.0972 ' (0xC0, BIOS 0x28) DOWN
12:35.0072 ' (0xC0, BIOS 0x28) UP -> 100ms
12:36.0072 LShift (0x10, BIOS 0x2A) DOWN
12:36.0082 3 (0x33, BIOS 0x04) DOWN
12:36.0172 LShift (0x10, BIOS 0x2A) UP -> 100ms
12:36.0182 3 (0x33, BIOS 0x04) UP -> 100ms
12:37.0172 \ (0xDE, BIOS 0x2B) DOWN
12:37.0272 \ (0xDE, BIOS 0x2B) UP -> 100ms
12:38.0271 Enter (0x0D, BIOS 0x1C) DOWN
12:38.0273 Enter (0x0D, BIOS 0x1C) UP -> 2ms

...
So the Arduino Keyboard library translates '#' into shift+3 which is unhelpful for UK users but I'm mystified why Keyhitter sees that '\\' produces the expected \ but other programs see it producing #! I guess Keyhitter intercepts keystrokes at a lower level than normal applications - for example it correctly shows Win being pressed but prevents Windows opening a start-menu.
The result in Notepad is typical of the effect produced in normal applications. So that's probably more relevant.
I can work around the '#' producing a shift+3 since '\\' produces # but how then do I generate a \?

try for (byte i = 0; i <= 255; i++) { Keyboard.press(i) .......  .... one of the values should generate the desired character ... then use that value instead of '\\'

@jsotola: I'm a bit wary of inadvertently hitting sequences of special keys like Win followed by  say F1 - so I tried an app that I suspect captures keystrokes at a low level - but that wasn't too helpful. I may try your suggestion if I can work in some safeguards so that I have time to work out what's happening before the system descends into a frenzied chaos.

figure out the byte value that represents the Win key and exclude it ... if ( i != Win ) Keyboard.press(i);

@jsotola: I was sceptical but that approach worked. I had to use a button press to increment my index because you encounter a lot of function keys etc causing help windows and other weird things to happen that you need time to recover from with a real keyboard. Keyboard.press(0xEC) produces "" in Notepad and when used in conjunction with shift produces the expected "|".

The USB keyboard protocol has no concept of characters. It doesn't know and doesn't care what character a key represents. Instead each code represents the location of the key on the keyboard, and it's down to the software on the computer to map those locations into characters through its own keyboard map.
So the Arduino has to do the opposite when you want to "print" text through the keyboard - convert that text into the locations of the keys on the keyboard. And it does that through the _asciimap array in Keyboard.cpp.
To use any other keyboard layout than US you need to modify that map so that each ASCII value points to the correct location for that character as defined in your computer's keyboard map.
You can find the list of keyboard location codes (named in this document after the US keycap decals) here (page 53) which you can then use to map any changes.
For example in _asciimap a double quote is listed as:
     0x34|SHIFT,    // "

Which maps to Keyboard ' and " in USB. But for UK you want that to be shift-2, which is Keyboard 2 and @ in a US layout.  That entry is hex 1F.
So changing the quote to be a shifted 0x1F should give you the quote you desire:
    0x1F|SHIFT, // "

You would need to do the same to all other characters that need re-mapping (including ). Some may take a little trial and error to work out what the equivalent key on a UK keyboard is, since some keys are in physically different locations (most notably there is no key to the left of Z on a US keyboard, but there is an extra one to the right of ]).
Unfortunately the Arduino Keyboard library doesn't provide a way for a user to give their own keyboard map. Instead you have to modify the source code of the library itself.

This makes sense but there is more going on because, on my Arduino-based keyboard, shift+2 already produces " rather than @ - so there's some additional mapping in Windows that's already doing most of the work of making my keyboard behave like an ISO-UK keyboard. (If interested Keyboard.press(0xEC) is an effective UK "" key. This whole area seems a lot more complex than I remember back in the days of PC-XT keyboard scancodes and TSRs

For completeness I am posting this answer. You can produce a UK backslash keystroke event by using something like
#define KEY_BSLASH 0xEC

This was found rather more empirically than analytically so is not an especially informative result, but it might be of some use to others creating non-ANSI keyboard layouts using Arduinos.

If it works on ISO-UK, it is likely to work on every ISO layout (e.g. give “<” in AZERTY). And this makes your answer more generally useful.

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


text:
Bluetooth HID module
I try to build custom controller and now searching for bluetooth hid module. Which BT HID module compatible with arduino? (not bluetooth serial)
List of some modules:

BlueSMiRF HID - from sparkfun, expensive (based on rn-42, also available RN-42-EK evaluation board) ✔ compatible
HM-10 bluetooth module - around $10 (aliexpress), based on cc2540 ht
tp://www.ti.com/product/cc2540
HC-05 Transceiver Module  - less $10, maybe supports HID after firmware upgrade(??)
Bluegiga wt12
Bluefruit EZ-HID from Adafruit ~$20 (suggested by mwwalk) ✔ compatible

Thanks

What do you mean by (not bluetooth serial)? Also, what's the objective of the question? All of those should be compatible with Arduino...

Module should support Human Interface Device protocol (HID), after connection to host system you can use it as keyboard/mouse etc, bluetooth serial port works like serial and if you want send keyboard signal you need additional software on computer (serial to hid)

Ahh, apologies I totally missed the whole HID thing... apologies again :)

The HM-10 is a BLE module incompatible with legacy bluetooth.  Some recent smartphones and other devices can talk both protocols, but be sure yours supports BLE (and for your intended usage) before you go with that option.  Also realize you need firmware for the module, either custom or a configuration of a factory firmware which meets your needs.

I'm not entirely sure from your question if you want just the module or a whole breakout board.  If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535

Thanks for your suggestions! I would like to buy this item, unfortunately adafruit don't ship items to my country and don't accept payments from cards.

Anyway, I bought Bluegiga wt12 (bare module) only for $12 from ebay and now making pcb. Bluegiga have very good website and a lot of useful documents.

HC-05 HC-06 and, for example, RN-42 HID are the same looking on hardware design.
Only difference is in firmware.
For educational purposes you can dump firmware from RN42HID and flash HC-05/06 module and you've got a HID module.
The difference in costs of the HID modules is that CSR IDE costs $3000 per licence  + developer seat, and when someone invests in developing wants the incomes to come.
Byron's blog will guide you, you need a SPI programmer, but you can use Arduino as programmer/debugger. And you will need blueflash software to backup some info from Your module (calibration of crystal for example, and IDS/MAC/serial) than you can flash the RN firmware, and you have exact copy of RN, last thing is to restore the settings saved from your original firmware.
Just Google it, here is not much place to put all the data and images.
But yes it is possible.


text:
Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode
This is a follow up to my previous question.
I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).
The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.
I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.
In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.
I have the following minimal(-ish) example:
#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

Ideally the ISR would just consist of PORTD |= (1 << PD3); but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.
Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).
Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?
I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

I think a potential solution might be to, in the interrupt, activate set on match, force a match, and then set it back to clear on match (and possibly force a match again if I detect the forced and "real" matches overlapped). I can't try this out until this afternoon, and it still seems needlessly complicated.

Why don't you use mode 7 instead of mode 2? Mode 7 combines CTC with fast PWM, which seems to be what you want, although it's not officially called “CTC” (but why would you care about the official name?).

Use Edgar's solution. Or use ISR(TIMER2_COMPB_vect) to set the pin to low, but this isn't ideal.

That makes sense. It seems I should have read the answers I got to my original question more carefully. Thanks. I'm not sure if I should delete this now (since a more careful reading of the original question solves my problem), but I am still interested why what I came up with doesn't work and what the use of "clear on match" in CTC mode is. Also, I think this is a strong case of me suffering from the XY problem.

The PWM modes manage pin at both ends of the cycle.
The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.
To manage both ends explicitly, you use normal mode.
To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:
ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}


text:
Problem with Arduino Uno and SIM900 shield logical communication (rx & tx)

The logical communication(rx & tx) between the shield and Arduino Uno doesn't  work. Arduino (rx & tx) supply  is 0 & 5 V but this is 0 & 2.8 V. What am I to do?

Post a link to where you bought the shield. It's extremely unlikely that a shield designed to plug right into a 5 V board would not also include any necessary level shifting circuitry.

Use a logic level converter.
A logic level converter is a small device that converts between different logic levels, for example between 5V and 3.3V.
I am not affiliated with Sparkfun, I just think they are the most informative source.

I think ur right


text:
4WD Arduino sketch problem
Here is the code:
/**  * @file         Arduino UNO Autonomous Robot  * @author       Calin Dragos for intorobotics.com  * @version      V1.0  * @date
      13.10.2016  * @description  This is an Arduino sketch for an autonomous robot able to detect and avoid obstacles  */
#include <AFMotor.h>
#include <Servo.h>
#include <NewPing.h>
Servo myservo;
int ENABLE_A = 6;
int PIN_A1 = 3;
int PIN_A2 = 2;
int ENABLE_B = 11;
int PIN_B1 = 5;
int PIN_B2 = 4;
int SENSOR_DISTANCE;
int LEFT_SENSOR_DISTANCE;
int RIGHT_SENSOR_DISTANCE;
int SNZ_DISTANCE_L;
int SNZ_DISTANCE_R;
int LFT_SNZ_DIS;
int RGT_SNZ_DIS;
#define TRIG_PIN 7
#define ECHO_PIN 8
#define MIN_DISTANCE 40
#define MAX_DISTANCE 200
#define INTERVAL 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  //pin mode for the DC motors
  pinMode (ENABLE_A, OUTPUT);
  pinMode (PIN_A1, OUTPUT);
  pinMode (PIN_A2, OUTPUT);
  pinMode  (ENABLE_B, OUTPUT);
  pinMode (PIN_B1, OUTPUT);
  pinMode (PIN_B2, OUTPUT);
  //pin mode for the ultrasonic sensor
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  //for servo motor
  myservo.attach(9);
  //set the ultrasonic sensor to center
  sensorCenter();
  //stop the motors
  stopMotors();
}

void loop() {
  SENSOR_DISTANCE = sensorDistance();
  Serial.print("Front sensor distance is: ");
  Serial.println(SENSOR_DISTANCE);
  if (SENSOR_DISTANCE >= MIN_DISTANCE || SENSOR_DISTANCE == 0) {
    goForward();
    Serial.println("Go forward");
  }
  else {
    //stop the motors
    stopMotors();
    LFT_SNZ_DIS = toTheLeft();
    RGT_SNZ_DIS = toTheRight();
    if (LFT_SNZ_DIS >= MIN_DISTANCE && LFT_SNZ_DIS >= RGT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_LFT;
      //try three times to escape
      for (int i = 1; i <= 3; i++) {
        goLeft();
        Serial.println("Go left");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_LFT = sensorDistance();
        if (NEW_SNZ_DIS_LFT >= MIN_DISTANCE)
        {
          break;
        }
      }
      sensorCenter();
    }
    else if (RGT_SNZ_DIS >= MIN_DISTANCE && RGT_SNZ_DIS >= LFT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_RGT;
      //try three times to escape
      for (int j = 1; j <= 3; j++) {
        goRight();
        Serial.println("Go right");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_RGT = sensorDistance();
        if (NEW_SNZ_DIS_RGT >= MIN_DISTANCE)
        {
          break;
        }

      }
      sensorCenter();
    }
    else
    {
      goBackward();
      Serial.println("Go backward");
      delay(500);
      //stop the motors
      stopMotors();
      sensorCenter();
    }
  }
}

void stopMotors() {
  analogWrite (ENABLE_A, 0);
  analogWrite (ENABLE_B, 0);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, LOW);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, LOW);
}

int sensorDistance() {
  int distance;
  int uS = sonar.ping();
  distance = uS / US_ROUNDTRIP_CM;
  if (distance != 0) {
    return distance;
    delay(300);
  }
}

void goForward() {
  analogWrite (ENABLE_A, 255);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite (PIN_A2, LOW);
  analogWrite (ENABLE_B, 255);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void goBackward() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goLeft() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite  (PIN_A2, LOW);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1,  LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goRight() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void sensorCenter() {
  myservo.write(90);
  delay(500);
}

void turnSensorLeft() {
  myservo.write(120);
  delay(500);
}

void turnSensorRight() {
  myservo.write(60);
  delay(500);
}

int leftSensorDistance() {
  int LEFT_SENSOR_DISTANCE;
  LEFT_SENSOR_DISTANCE = sensorDistance();
  return LEFT_SENSOR_DISTANCE;
}

int rightSensorDistance() {
  int RIGHT_SENSOR_DISTANCE;
  RIGHT_SENSOR_DISTANCE = sensorDistance();
  return RIGHT_SENSOR_DISTANCE;
}

int toTheLeft() {
  int LEFT_SENSOR_DISTANCE;
  turnSensorLeft();
  LEFT_SENSOR_DISTANCE = leftSensorDistance();
  Serial.print("Left sensor distance is: ");
  Serial.println(LEFT_SENSOR_DISTANCE);
  return LEFT_SENSOR_DISTANCE;
}

int toTheRight() {
  int RIGHT_SENSOR_DISTANCE;
  turnSensorRight();
  RIGHT_SENSOR_DISTANCE = rightSensorDistance();
  Serial.print("Right sensor distance is: ");
  Serial.println(RIGHT_SENSOR_DISTANCE);
  return RIGHT_SENSOR_DISTANCE;
}

Here is the error that I am getting:
Arduino: 1.8.6 Hourly Build 2018/05/28 09:33 (Windows 8.1), Board: "Arduino/Genuino Uno"
In file included from C:\arduino-nightly\hardware\arduino\avr\cores\arduino/Arduino.h:257:0,
                 from sketch\intorobotics.ino.cpp:1: C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected unqualified-id before numeric constant
#define PIN_A1 (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected ')' before numeric constant
#define PIN_A1   (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected unqualified-id before numeric constant
#define PIN_A2 (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected ')' before numeric constant
#define PIN_A2   (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output
during compilation" option enabled in File -> Preferences.

I was going to answer your question but instead I had to spend that time cleaning up the garbage formatting you dumped on us by using quote markup instead of code markup on your code and error message. Super disrespectful to the people you're asking for free help.

I'm so sorry....I tried but was getting bold and heading texts

It looks like you've chosen names for your variables that are being used by the core.  Pick different names for those variables.

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


text:
NodeMCU (Arduino IDE) 'DynamicJsonBuffer' was not declared in this scope
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;
String url = "http://192.168.31.170/api/mode/qwertyui";

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

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Robotics Incubator", "XXXXXXX");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    HTTPClient http;
    http.begin(url); //HTTP
    int httpCode = http.GET();

    if (httpCode == 200) {
      // Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
      DynamicJsonBuffer jsonBuffer(bufferSize);  //This was not declared error.
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      int Mode = root["mode"]; // 1
      Serial.print("Name:");
      Serial.println(Mode);
    }
    http.end();
  }

  if (Serial.available()) {
    url = Serial.readString();
  }
  delay(100);
}

How can I solve this problem?
I followed this tutorial - ESP8266: Parsing JSON

This error is caused by using a 6.x.x version of the ArduinoJson library with code that was written for a pre-6.x.x version of the library.
You have two options to solve the problem:
A. Downgrade the library to a version that is compatible with your code
For now, this is probably the best option because the 6.x.x version of the ArduinoJson is still in beta so it makes sense to wait until the new API is stabilized before porting your code. This is even recommended by the ArduinoJson developers:
https://arduinojson.org/v5/faq/error-jsonbuffer-was-not-declared-in-this-scope/

Sketch > Include Library > Manage Libraries...
Wait for the download to finish.
In the "Filter your search..." box, type: "arduinojson".
Click on "ArduinoJson by Benoit Blanchon".
From the "Select version" dropdown menu, select "Version 5.13.2".
Click "Update". Wait for the update to finish.
Click "Close".

Now your code will compile. If you have File > Preferences > Check for updates on startup enabled, you will continue to get updatable library notification for the ArduinoJson library but you need to refrain from updating back to a 6.x.x version or the error will come back.
B. Update your code to be compatible with the 6.x.x version of the ArduinoJson library
In this case you need to modify your deserialization code to use the new DynamicJsonDocument instead of the old DynamicJsonBuffer:
if (httpCode == 200) {
  // Parsing
  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
  DynamicJsonDocument jsonDocument(bufferSize);
  DeserializationError error = deserializeJson(jsonDocument, http.getString());
  if (error) {
    Serial.println("There was an error while deserializing");
  }
  else {
    JsonObject root = jsonDocument.as<JsonObject>();
    // Parameters
    int Mode = root["mode"]; // 1
    Serial.print("Name:");
    Serial.println(Mode);
  }
}

You can get more details about this here:
https://arduinojson.org/v6/doc/upgrade/

This answer needs to be updated for anyone who visits here.
The 6.x.x is no longer in beta.
Simply update to the latest version. At the time of writing this answer the version id is 6.15.2. Updating to this will resolve the error.


text:
Can't upload code to an Arduino LilyPad using FTDI
I've tried to upload my code to an Arduino LilyPad (328) using an FTDI basic breakout, but i get this:
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x29

I tried to install the latest FTDI drivers from the FTDI website, tried another PC, tried to install the CDM-2.08.28 driver (latest I think) and nothing.
If I change the PC port the USB Serial Port doesn't change (is always COM3).

Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back.  If, you have FTDI problems that you need to resolve.

Hi, i can't do the loopback test because i have no jumper cables at the moment, i've done the loopback test on the FTDI breakout using PuTTy, and when i press any keyboard key the Rx LED on the FTDI blinks, anymore tests?

solved ! was able to upload code choosing arduino uno instead of the lilypad (baud reasons if im correct)


text:
Maintain delay with NEO-6M
Ì am building speedometer with NEO-6M and have some problems with my code.
The scenario is that I send some data from our Arduino to another device via a TX pin with a delay of 50 ms. This delay of 50 ms needs to be maintained and should not exceed. The issue with GPS data, which arrives from the device, is that it is received every 1 second. This issue will cause the 50ms delay to be longer and exceed to 1050 ms. In my last code change delay is not maintained on 50 ms, it is all 1000 ms. Not sure what I did wrong.
My code is
original
#include <AD9850.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 0, TXPin = 1;
static const uint32_t GPSBaud = 9600;

const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN = 10;
const int RESET_PIN = 11;

double freq = 1;
double trimFreq = 124999500;

int phase = 0;

unsigned int speed = 0;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);
}

void loop()
{
  // Dispatch incoming characters
  while (ss.available() > 0)
    gps.encode(ss.read());

  {
    digitalWrite(outPin, HIGH);   // sets the pin on
    delayMicroseconds(50);        // pauses for 50 microseconds
    digitalWrite(outPin, LOW);    // sets the pin off
    delayMicroseconds(50);        // pauses for 50 microseconds
  }

  if (gps.speed.isUpdated())
  {
    Serial.print(F("SPEED      Fix Age="));
    Serial.print(gps.speed.age());
    Serial.print(F("ms Raw="));
    Serial.print(gps.speed.value());
    Serial.print(F(" km/h="));
    Serial.println(gps.speed.kmph());
    speed = gps.speed.kmph();
    //calculate the frequency with map()
    freq = map(speed, 0, 100, 0, 160);
    DDS.setfreq(freq, phase);
  }
}

revised
(replying to https://arduino.stackexchange.com/a/45657)
Thank you for help. Is it possible to put GPS speed in this code? https://pastebin.com/LdT7UHBQ I used your code and it works but my boss demands that we modify his code and make it maintain delay with it.
long prevTxTime = 0;
const int delayTime = 51;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);
}

void loop()
{

  int b, chunk = 0;

  if (Serial2.available())
  {
    b = Serial2.read();
    chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;
      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1] << 6);
        velocityfreq = bytes[2] + (bytes[3] < delayTime)
        {
          //speed from gps would most likely need to be set here as "speedfromgps"

          SendData();
          prevTxTime = millis();
        }
      }

      void SendData()
      {
        sprintf(charToSend, "%d|%d|%d|%d|%d\n\r",
                data1, data2, data3, data4, speedfromgps);

        Serial1.print(charToSend);
      }

Thank you for help. Is it possible to put gps speed in this code? pastebin.com/LdT7UHBQ I used your codeand it it works but my boss demands that we modify his code and make it maintain delay with it. long prevTxTime=0; const int delayTime=51; void setup() { Serial1.begin(115200); Serial2.begin(115200); } void loop() { int b, chunk = 0; if (Serial2.available()) { b = Serial2.read(); chunk = b >> 6; if (chunk == syncc) { bytes[syncc] = b & 63; syncc++; if (syncc == 4) { syncc = 0; tach = bytes[0] + (bytes[1]<<6); velocityfreq = bytes[2] + (bytes[3]< delayTime) { //speed from gps would most likel

What is outPin?
Don't start a SoftwareSerial object on the Serial port.  Just use Serial
The Serial Monitor window will have to use the GPS baud rate if the GPS is connected to pins 0 & 1.  This is a good choice, but you'll have to disconnect pin 0 to upload a new sketch over USB.
Don't use delay.  This prevents the sketch from reading GPS characters.  Eventually, the input buffer will overflow and characters will be lost.  Instead, save a timestamp and compare the current time with the timestamp.  When the difference is 50ms, simply toggle the pin and save another timestamp.
Try NeoGPS.  It's smaller, faster, more reliable and more accurate than all other GPS libraries.  There are many tips on the Installation and Troubleshooting pages, and the examples are structured properly.  If you want to use pins other than 0 & 1, be sure the read the section about choosing a serial port.  SoftwareSerial is the worst choice.

Here is your sketch, modified to use Serial and NeoGPS:
#include <AD9850.h>
#include <NMEAGPS.h>
NMEAGPS gps;

#define gpsPort Serial  // GPS on pins 0 & 1
static const uint32_t GPSBaud = 9600;

const int OUT_PIN   = 4; ???
const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN  = 10;
const int RESET_PIN = 11;

const double trimFreq = 124999500.0;

int phase = 0;

unsigned long lastToggle;

void setup()
{
  //Serial.begin(115200);  // NOT needed if gpsPort *is* Serial (pins 0 & 1)
  gpsPort.begin( GPSBaud );

  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);

  pinMode( OUT_PIN, OUTPUT ); // must be set to output mode
  lastToggle = millis();
}

void loop()
{
  // Toggle the OUT_PIN every 50ms
  if (millis() - lastToggle > 50) {
    digitalWrite( OUT_PIN, !digitalRead(OUT_PIN) );   // toggle the pin
    lastToggle += 50; // step to the next toggle time
  }

  // Dispatch incoming characters
  if (gps.available( gpsPort )) {
    gps_fix fix = gps.read(); // get a fix structure with all GPS fields

    Serial.print(F("SPEED km/h="));

    // for testing, use some random values (comment this out later)
    fix.valid.speed = true;
    fix.spd.whole   = random( 0, 35 );

    if (fix.valid.speed) {
      float speed=fix.speed_kph();
      Serial.print( speed );

      double freq = map(speed, 0, 100, 0, 160);
      DDS.setfreq(freq, phase);

      Serial.print( ' ' ); // for debugging, show the DDS frequency
      Serial.print( freq );
    }
    Serial.println();
  }

}

Notice that it checks to see if there is a valid speed.  The GPS device may not know the speed, depending on satellite reception.
If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.

UPDATE
For the code you posted (which is not a complete program) in an Answer (instead of editing your question :-/), you could do something like this:
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#define gpsPort Serial  // GPS on pins 0 & 1 or whatever
static const uint32_t GPSBaud = 9600;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);

  gpsPort.begin( 9600 );

    ...other things?
}

void loop()
{
  // Constantly read GPS characters
  if (gps.available( gpsPort )) {

    // Update the global fix structure with the latest GPS info.
    //   The speed will be used later by SendData.
    fix = gps.read();
  }

  // Constantly read Serial2 characters (a sensor?)
  if (Serial2.available())
  {
    int b     = Serial2.read();
    int chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;

      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1]<<6);
        velocityfreq = bytes[2] + (bytes[3]< delayTime)  ??? "<" ???

        SendData();
        prevTxTime = millis();
      }
    }
  }
}

void SendData()
{
  // No need to use sprintf, just print the pieces.

  Serial1.print( data1 );
  Serial1.print( '|' );
  Serial1.print( data2 );
  Serial1.print( '|' );
  Serial1.print( data3 );
  Serial1.print( '|' );
  Serial1.print( data4 );
  Serial1.print( '|' );

  // use the current GPS speed, as set in loop
  Serial1.print( fix.speed_kph() );
  Serial1.print( F("\r\n") ); // F macro saves RAM for doubled-quoted string constants
}

I had to guess at the nesting of curly braces because IT IS NOT INDENTED, nor do the CURLY BRACES MATCH.  sad.

Hi. Thank you for help. Is it possible to put gps speed in this code? https://pastebin.com/LdT7UHBQ I used your codeand it it works but my boss demands that we modify his code and make it maintain delay with it.

Nope, not even.  His code is wrong in all the ways I described, especially regarding delay.  It is ok to use a delay on a PC where there is an OS to manage multiple tasks, but it is the worst thing to use in an embedded program where there is no OS.  If your boss cannot learn new techniques to solve his problems, then you need a new boss.

Hahaha that is what i am telling to myself last 5 months


text:
Limit to number of sensors attached to Arduino
Is there any limitation on how many sensors can be attached to one Arduino board? I am making elderly smart ban and I want to use GPS, GSM, gyroscope, pulse sensor, temperature sensor and I2C OLED. Right now I have only gyroscope, pulse sensor and GPS connected to Arduino Uno but I would like to add more stuff and also I am considering using Arduino Nano or only ATmega328P chip for finished product. My main concern is power.

Power is a concern, but the number of available pins is the more-limiting factor.  Even so, these units (I use Nano a lot) can easily handle several sensors simultaneously.  Mine output to Raspberry Pi via Serial cable so it can collect data for later processing.

There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

Can you fit all the code in flash, and the required variables in RAM?
Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.
For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.

Thank you for advice. For code it is ok, it fits. But i am worried for power. Idea for now is to add more batteries

Calculate how much current you need for your sensors first. No one can help you until you do that.


text:
ESP8266WiFi client.print() strange response
I am using a NodeMCU, so ESP8266. I installed the core via the Boards Manager at the last version.
My goal is to control a GoPro camera through WiFi.
I am getting mad with these few lines of code:
uint8_t GoProControl::sendRequest(String request) {
    client.stop();
    if (!client.connect(_host.c_str(), _port)) {
        if (debugStatus){
            Serial.println("Connection lost");
            GoProConnected = false;
        }
    return false;
    }

    client.print(request);
    client.print("Connection: close\r\n\r\n");

    if (debugStatus){
        Serial.println("my request is:");
        Serial.println("-------------");
        Serial.print(request);
        Serial.print("Connection: close\r\n\r\n");
        Serial.println("-------------\n");
    }
    if (listen() == "HTTP/1.1 200 OK\r") {
        return true;
    }
    else {
        return false;
    }

}

the client is connected without problem (it never gives me error) and so i send the request:
GET http://10.5.5.9/camera/SH?t=password&p=%00 HTTP/1.1
Connection: close

the listen function mainly does:
char c = client.read();
response += c;

and then print the response, this is what i get from it:
HTTP/1.1 404 Not Found
Connection: close
Date: Sat, 13 Jan 2018 16:26:27 GMT
Server: Cherokee/1.2.101b150604_3b16072 (UNIX)
Content-Length: 355
Content-Type: text/html
Cache-Control: no-cache
Pragma: no-cache

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>404 Not Found</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

404 Not Found

The requested URL /camera/SH was not found on this server.

Cherokee web server 1.2.101b150604_3b16072 (UNIX), Port 80

It looks like I am connected to the wrong host.
Since I am sure that this is the correct request, where is possible that I am doing any error?

can you connect to it with your computer?


text:
Reading Arduino Serial Input
I am reading an input from my Ohaus weighing scale using it's RS232 output using this code:
#define HWSERIAL Serial1

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

void loop() {
  int incomingByte;

  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("USB received: ");
    Serial.println(incomingByte, DEC);
    //HWSERIAL.print("USB received:");
    //HWSERIAL.println(incomingByte, DEC);
  }
  if (HWSERIAL.available() > 0) {
    incomingByte = HWSERIAL.read();
    Serial.print("UART received: ");
    Serial.println(incomingByte);
    //HWSERIAL.print("UART received:");
    //HWSERIAL.println(incomingByte);
  }
}

When pressing the print button on the scale, I was expecting data to come over in single burst with just the readings, but what I am getting is the expected data, but the scale keeps sending data afterwards (ES over and over). I need to parse out just what's needed. The below is the output from the console on my computer.
UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 0
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: (This is a CR)

UART received: (This is a LF)

UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 4
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: G
UART received:
UART received:
UART received: (CR)

UART received: (LF)

UART received: E
UART received: S
UART received: (CR)

UART received: (LF)
... (The ES loops over and over until the print button is pressed again)

0.00 is the current scale reading and 0.40 is the tare weight. That's all I need and I can't figure out how to parse it. The blocks aren't the same length so how do I pull out the needed information and ignore the repetitive 'ES'? I'm not 100% sure if I'm even going about this the right way?
Output as DEC
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 48
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 13
UART received: 10
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 52
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 71
UART received: 32
UART received: 32
UART received: 13
UART received: 10
UART received: 69
UART received: 83
UART received: 13
UART received: 10
UART received: 69
UART received: 83
...

From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226 > The balance will return “ES” for invalid commands. Check to make sure you're using the correct serial parameters that the RX line is wired correctly.

Can you give a full working sketch and a output that is actually from that sketch. Make incomingByte an int, and remove the cast to char when you print it. Print it as DEC or HEX, so you can see the numbers of the characters or spaces or linefeeds or other fancy bytes.

Is that a real RS-232 signal? What do you use to convert it to a ttl-level signal? If you use a module, tell us which module. Add to you question the model of the weighting scale. The document mentioned by @jdwolf show different formats for different models. The 'g' is the unit and the '?' is unstable. The rest should fit into one of the formats. I suppose the two character 'term' is the cr lf.

Well, I tried to use a Max 3232, but for some reason, the scale wasn't pushing enough voltage to trigger it to send the ttl, so what I did was connect it directly to pin 0 on the leonardo to get this readout and I actually got the above UART readings. The problem was that the 232 was sending some erroneous signals and causing issues. I don't understand why this worked, because RS232 is inverted from ttl, so my only assumption is that ohaus already converts their signal to ttl?

Noise on your TX line? Sounds like maybe your sending random data the device doesn’t understand.

I'm trying to do pretty much the same thing with an OHAUS Ranger 3000 scale. Have you figured out whether the signal coming from the OHAUS is at 5V TTL or 13V RS232? Thanks

From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226

The balance will return “ES” for invalid commands.

Check to make sure you're using the correct serial parameters that the RX line is wired correctly.

Thanks, that definitely helped. I just removed the TX line from the Arduino, as I'm not sending data to the scale.


text:
My Arduino Uno buzzer isn't working
/*

*/

void setup() // Built in initialization block
{
    Serial.begin(9600);
    Serial.println("Beep!");
}

void loop() // Main loop auto-repeats

{

//   Serial.println("Beep!");

   tone(4, 3000, 1000); // Play tone for 1 second

   delay(1000); // Delay to finish tone
}

Does this buzzer work when voltage is applied to it directly?  If so, then have you tried just turning it on with an output pin and then delaying while it buzzes?  Is it really a buzzer, or is it a piezo transducer?  I see a statement of the problem in the title, then a code snippet which is obviously your attempt to make it work, but I do not see a question.  Plus, as @Majenko and Delta_G point out, there are other questions that may answer this.  So I suggest you do some more research on this before posting.  This will need to explain why it is not a duplicate, at the very least.

This question is no longer a duplicate. The OP had an original question, https://arduino.stackexchange.com/questions/39087/why-is-the-piezo-buzzer-not-looping-making-sound, which was answered. Then they (incorrectly) modified that original question, to be the same as the original answer. Obviously they should not have done that. Then, they asked the same modified question again here, thereby making a duplicate of the original question (after it had been modified). Now that I have rolled back the original question, this question is no longer a duplicate, and as such should be reopened.

First, take a look at the two links provided in the comments to your question and explain why your question is different from them.  Start by describing your "buzzer."  If your question is not significantly different then it will attract downvotes instead of answers, or it may be marked as duplicate or just simply closed.
Here is one solution, making the assumption you are writing about a piezo beeper:
void setup() {
  pinMode(4,OUTPUT);
}
void loop() {
  digitalWrite(4,HIGH);
  delay(1000);
  digitalWrite(4,LOW);
  delay(1000);
}

Alternatively, take the first example program from your IDE, called blink, and hook your beeper to pin 13 (positive) and GND (negative) while that runs.  It does basically the same thing.

The two links go to the same question, that the OP has already asked... The problem is probably active/passive buzzer


text:
Stepper Motor with Limit Switches
I have the code below which is my attempt to control a stepper motor direction that moves a carriage to the right and left. In addition there are limits at each end of the travel that when activated stops movement in the respected direction. My problem is that the motor works just fine in the left and right directions but I can only get one of the limit switches to work. I'd appreciate any suggestions.
int PUL = 7; //define Pulse pin
int DIR = 6; //define Direction pin
int ENA = 5; //define Enable Pin
int RGT = 3;
int LFT = 2;
int potPin = A5;
int count = 0;
int interval = 1000;
int val = 0;
int Spd = 500;

#define Limit01 8  // Pin 2 connected to Limit switch out
#define Limit02 9  // Pin 3 connected to Limit switch out

void setup() {
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
  pinMode (ENA, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(LFT) == LOW) {  //  If joystick is moved Left
    if (digitalRead(Limit01) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor clockwise

      digitalWrite(DIR, LOW);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);
    }
  }

  if (digitalRead(RGT) == LOW) { // If joystick is moved right

    if (digitalRead(Limit02) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor counter clockwise

      digitalWrite(DIR, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);

    }
  }
}

You did not initialize the inputs. It looks like the switch has a pull-down, so no internal pull-up, but anyway initialize them at the beginning. Then.. Are you sure the switch is working? Did you try to use a sketch to read the switches state to check if they work?

Can you supply a schematic of how the switches are wired? Have you measured the voltages on the limit switch inputs with the switch in the open and closed positions?

What I understood from your question is you want only one limit switch to control the stepper motor in both directions.So here is the code that might be helpful for you in that case:
int dirpin_T1 = 2;
int dirH_T1 = 3;
int steppin_T1 = 4;
int limit = 10; // ASSUME LIMIT-SWITCH IS PLACED AT RIGHT CORNER
void setup() {
  pinMode(limit,INPUT);

  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);

}

void loop() { //STEPPER TRAVELLING LEFT TO RIGHT

    digitalWrite(dirpin_T1, LOW );
    digitalWrite(dirH_T1, LOW);
   do
   {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);

   }(digitalRead(limit)==HIGH); //AS LIMIT-SWITCH PRESSED MOTOR STOPS
  delay(500);
  //WHEN LIMIT-SWITCH IS LOW CHANGE THE DIRECTION OF MOTOR ROTATION
  if(digitalRead(limit)==LOW)
  {
      digitalWrite(dirpin_T1, LOW ); //CHANGE MOTOR DIRECTION (LOW TO HIGH)
      digitalWrite(dirH_T1, HIGH);
     for(int i=0; i<36000;i++)
      { //please try changing value of i as it depends on how much rotations you want your motor to step forward

      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
     }

  }
}

The simple logic would be to move the motor in one direction until limit-switch is HIGH. And to move it to the other direction when its LOW i.e already pressed.Correct me if I am wrong and try modifying the code as per this logic.However you need to change your code depending upon what type of driver you are using. Right now I am using TB6560 driver.You can use if loop instead of do while loop to make it easier to understand.

its a limit switch

thats a blank loop that will cause motor to stop when digitalRead(S01)==HIGH, otherwise motor will keep rotating

Earlier comment was missing so that led little confusion as above. Comments are lines in the program that are used to inform yourself or others about the way the program works. They are ignored by the compiler, and not exported to the processor, so they don’t take up any space in the microcontroller’s flash memory. Comments' only purpose is to help you understand (or remember), or to inform others about how your program works.

Use
while ( condition)
{ code to execute }
making sure the code itself is "short" not to overrun the condition
If you use while construct instead of do / while you are checking the condition first before code execution.
while( not at limit switch)
move stepper one step
Also the limit switch active state should be ground, not +V. Safety issue.
If you  accidentally ground the signal it will be valid, if the signal path is grounded already , by accident, putting  +V to it won't be detected.


text:
When I see the red RX LED flash I am wondering if it means there is an error?
Each time I press a particular button in my circuit the red RX light flashes briefly.
I have been having trouble with making this button perform the command it should, I and am wondering if the RX flash has something to do with that, or is at least reporting some sort of error?

Leds? Buttons? Which is it? Also, what the frog is a "red board", and what is this mystery circuit you have? And while you're at it, what code is supposedly trying to perform a "command"?

Welcome to Arduino beta.  Please take the tour to get the most out of this site:  https://arduino.stackexchange.com/Tour - You will notice the downvotes because of the way your question is formatted.  Take the tour and perhaps you can edit in a way that will attract answers.

The red light is flashing because you are pressing the button.  To stop the red light flashing I recommend not pressing the button.

The TX LED is there to show that some data or signal has been received on your Arduino. When you press the button on your circuit, it briefly sends a signal which then triggers the RX LED on your Arduino. Most often, the RX LED is used to troubleshoot whether you are receiving an input and, in your case, it seems you are.
Therefore, the RX LED is not an error and shouldn't be the source of your problem.


text:
if-else statement not working
So I'm facing this problem a lot in my code where the program is not getting into the if else loop properly and just returning the same answer again and again.
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));
if (temp == 0.00) {
temp2 = 0.00;
} else {
  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

The answer keeps on coming 0 even when temp is non zero.

If anyone knows the reason please help...

Please edit your question to show actual code used.  What's there now has a compile error with temp2 not declared before use.  Note, the temp2 declaration shown in the else branch has scope only within the else branch and is not available outside it.

Note that You may want to use atan2() instead of atan().

And also it's not a good idea to compare floats for equality, as they are not "exact" numbers. For example 0.00 can be anything between -0.0049999.... and 0.0049999..... (roughly)

The initialisation code is missing. Where is temp2 declared? and X-pin and Y_pin

You use doubles for everything and then use a value of 3.1416 for PI? 1) in arduino doubles are only 32 bit floats not true 64 bit doubles so the constant casting to double is unnecessary. 2) a 32 bit float is accurate to more than 5 figures so that Pi value is the limiting factor in your accuracy.

I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));

if (temp == 0.00) {
  temp2 = 0.00;
} else {

/* Bug here.                                                             */
/* this temp2 is local to these {} and is lost as soon as we reach the } */
/* at the end of the else.                                               */
/* Remove the word double and it should work                             */

  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

Personally I'd replace the entire if ... else with:
double temp = abs(tan(theta_rad)); // removed redundant casts to double

double temp2;
if (temp > 1.0) // 1/temp will be smaller if temp > 1
  temp2 = 1.0/temp;
else
  temp2 = temp;

It'll have exactly the same effect but avoids unnecessary floating point calculations


text:
How to read long value sent by Arduino in C
I have a quick question regarding this code below in Arduino:
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.println(5);

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

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

In C i defined:
char message[13];
uint32_t num;
char until = '\n';

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

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

I am expecting a raw value of 0501050105 first.
Then I convert this raw string into 501050105 using:
sscanf(message, "%d", &num);

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).
In addition, when i use serialport_read_until() method above, even though i specify the char until as '\n', the method terminates after reading '\r' (leaving the \n in the serial buffer), and the '\n' is only captured in the next method call.
Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?
Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.
Thank you very much.

What's the number you are sending? 501050105? or 51515?

@NickGammon currently we are sending 501050105 but we are thinking of reducing it to 51515 in future. Both will still be long in Arduino

What I am trying to ask is: What is the "actual" number you are sending? For example, could it be: 5,1,5,1,5? Are the zeroes part of the number or a delimiter?

@NickGammon yes we are trying to send 5,1,5,1,5 efficiently from arduino to C!! Not sure if theres any other efficient ways to do it. We currently reserve 2 digits for the 5 different variables, so i split them up with x%100 followed by x/100 and repeat 4 more times

The commas sounds much more sensible to me. What if you want to send a zero?

@NickGammon We will never ever send a zero (minimum value is 1). if we were to use comma, whats the efficient way to extract it out? strtoul, sscanf or others?

If you are always sending one digit, then the simplest is your suggestion of just packing them all together. Then just index into the received array, eg. message[0], message[1] and so on. And to convert back to a number, just subtract '0' from it.

@NickGammon ok thanks i will try out later and let you know!

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

No, it expects a pointer to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:
char b;
...
int n = read(fd, &b, 1);  // read a char at a time
...
buf[i] = b;
... etc ...

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

C has the function strtoul() which is far more efficient that sscanf.
uint32_t val = strtoul(buf, NULL, 10);

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

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

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

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

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

Thanks for the feedback! That was a typo! It's char newLine = '\n'; Not sure why it still cuts at \r. Could it possibly be because of something like this? https://github.com/todbot/arduino-serial/issues/9 Could I be missing something like this? options.c_iflag &= ~ICRNL; // Don't Map CR to NL


text:
Arduino serial communication input string checking
I am trying to check whether the input string in my serial is inside my string array, but it seems like that the condition if(array[i]==inputString) does not print true.
So here is my code:
String array[4]={"hey","jude","jane"},inputString,test;
boolean stringComplete=false;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  //int store=0;
  serialEvent();
  if(stringComplete){
    Serial.println(inputString);
    for(int i=0;i<4;i++){
      Serial.println("..");
      //test=array[i];
      Serial.println(array[i]);
      if(inputString==array[i]){
        Serial.println("true");
        break;
      }
    }
  inputString="";
  stringComplete=false;
  }
   //Serial.println(store);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

could you please change the image by actual text for the code ? Thanks.

First, you declare an array of 4 items and provide an initializer for 3. Don't know how it can even compile, maybe it is tolerated but in doubt
String [] array = {"hey","jude","jane","foo"};

Also, your serialEvent function appends \n to the string. Even if you receive string jane, you will compare jane from array with jane\n from serial
char inChar = (char)Serial.read();
if( inChar == '\n')
   stringComplete = true;
else
   inputString += inChar

No reason to doubt, just look it up.  See paragraph 19 (the “all subobjects that are not initialized explicitly shall be initialized implicitly the same as
objects that have static storage duration” sentence) in part 6.7.9 of the ISO/IEC N1570 C++ standard.  The 4th item of String array[4] will be initialized to a null pointer if only three initializers appear.

Thanks for the input, but then even with the sentence it's not entirely clear to me. 4th item will be initialized to nullpointer or String with empty constructor ?

The empty string (ie. String with the default constructor).

It occurred to me after commenting that "null pointer" might be incorrect for String objects, but didn't know offhand.

A String object isn't a pointer, so it can't contain a null pointer, per se.


text:
How does supply voltage affect `analogRead()` on AVR-based microcontrollers?
I'm using an ATmega328P based Arduino to prototype reading a TMP36 temperature sensor. I will eventually move this to an ATtiny85 based board with a battery supply. Both the TMP36 and ATtiny85 have a Vcc range from 2.7V to 5.5V so a battery that starts at say 4.5V and slowly drops to 2.7V should not be out of range.
I am expecting to read temperatures in the range -5°C to +30°C which should correspond to a TMP36 output between 0.5 to 0.9V. I am getting 0.74V at around 23°C so this sort of range seems plausible.
The TMP36 outputs 10 mV/°C regardless of Vcc (within 2.7-5.5v). But I suspect the AnalogRead() value will be scaled by the supply voltage and so will slowly change as the battery drains. Is this correct?
Do I need to include an external voltage-regulator / voltage-reference device to supply some fixed voltage (e.g. 2.5V) to AREF?

Solution
Following Edgar Bonet's Answer I successfully enabled the internal voltage reference for the ADC.
Initially I added a 100nF bypass capacitor to AREF and tried
#define REFS1 7
#define REFS0 6
#define REFS2 4

...
//ADMUX = (_BV(REFS1) | _BV(REFS2)); // 2.56V ATtiny85   datasheet §17.3 pp134
ADMUX = (_BV(REFS1) | _BV(REFS0)); // 1.1V  ATmega328P datasheet §23.9 pp217

but didn't get it to work, my code had no effect on values from analogRead(). So after a bit of further reading I instead used
analogReference(INTERNAL);

Which worked.

The ADC measures a voltage ratio. The conversion result is the rounded
value of 1024×V/Vref, where V is the voltage at the input and
Vref is the voltage reference.
In the default Arduino configuration, the reference is connected to Vcc.
This will not fit your use case, as the voltage you want to read does
not vary proportionately to Vcc. You could use an external reference.
However, the ATtiny85 has two internal voltage references at 1.1 and
2.56 V. Either of these may be well suited for you application,
which should save you having to add an extra part.
See the chapter on the ADC in the datasheet for details on
how to select the voltage reference.

Thanks, that quickly led me to a solution - new notes appended to question for those  interested.


text:
Level shifter with diode - not pulling to zero
I'm interfacing a 3.3 V device (a GPS module with a serial interface) to a 5 V Arduino Nano. The circuit I am using is this:

simulate this circuit – Schematic created using CircuitLab
I don't have the GPS Module connected at the moment and have added LED D1 and R2 to visualise the Arduino TX signal (which is currently just setting TX GPIO pin high and low on a 1 second cycle). I am measuring the voltage at NODE1 with a DMM.
My understanding is that D3 blocks the 5V high from Arduino TX and then NODE1 is pulled to 3.3 V by R1. When Arduino TX is low (0 V) D3 conducts and pulls NODE2 to 0 V.
What I measure at NODE1 is 3.1 V and 0.8 V. Am I right in thinking that ...

The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor. The RX input of the GPS module will have some similar effect.

The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148? Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?

This is pretty much OK and as expected.

The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor.

Correct.

The RX input of the GPS module will have some similar effect.

No, the RX will have little to no effect. It is "high impedance" - looking to the circuit like a very small capacitor and very large resistor in series to ground. Negligible to your circuit.

The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148?

Yes. The datasheet shows the forward voltage can be up to 1V.

Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?

No.

This is pretty much OK and as expected.

It is.

Now my comments:

You should use a larger pullup and isolate your LED (if you want to keep it) with a BJT or MOSFET so it doesn't load the circuit. That will reduce the current and thus the forward voltage drop over the diode slightly.
You should use a Schottky diode to considerably reduce the forward voltage drop even further. These also switch faster allowing for higher baud rates.

That is correct. The most reliable solution is to use a level shifter. They are inexpensive and generally come with more than 1 channel. Use one of the additional channels to drive your led. You are reducing your logic low to 0.32 volts. Typically the threshold is 40% of VCC or 1.32 volts. - 1 volt (worse case) for the 4148 uses almost all of your marjin. That can be reduced even further by loads on the pins. The level shifter is one small board, not a handful of parts to connect which increases your chance of errors but it will help your debugging skills.


text:
millis() vs creating a "long" variable
I think my issue is not fully understanding how the millis() function works;
I am wondering the difference between simply creating a variable such as
long fake_millis  ++ ;

vs using millis()?

millis() returns an unsigned long, not a long. It is never negative.

Besides the unsigned issue, how would you manage to do fake_millis++; exactly once per millisecond? Think about it: it's not so simple, especially if the program is busy doing other stuff. Best solution would be to do it from a timer interrupt. Once you do that, you have essentially reimplemented millis().

millis() returns the ACTUAL time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, millis() will still return the right time.
The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.
I short, just use millis(). It is easy to use and works great.
P.S. Use an unsigned long instead of a long.

appreciate the response.  I am wondering though for this basic formula where i just need to have a "second" counter, http://pastebin.com/raw/hxcVukR7    could  i just replace Millis() with my method ?

@danieljay, for that simple example, maybe, but for more complex programs, stick with millis()


text:
How to connect TFT screen (ST7735S) to Arduino?
I'm learning to work with Arduino and I decided to work with a TFT display (driver ST7735S, I connect to Arduino Uno), but I encountered a problem in the form that my contacts are labeled differently than in all the examples I looked at (example - no MOSI contacts/ MISO and CLK, instead of BL - BLK), because of which I am confused and cannot connect the screen correctly -
please, help)
Display photo:

what are the pin labels?... you only said what they are not, which is not very useful ... please update you post

Connections
Connections as follows:

BLK -> 5V
CS -> D10 (or anything, i.e. D9 -  just change the #define below)
DC -> D9 (or anything, i.e. D8 -  just change the #define below)
RST -> D8 (or anything, i.e. D7 -  just change the #define below)
SDA -> D11
SCL -> D13
VDD -> 5V
GND -> GND

Using TFT library
You can use the TFT library:
#include <TFT.h>
#include <SPI.h>

With the following #defines:
#define CS 10
#define DC 9
#define RST 8

Note: if you used different pins, then just change the numbers.
Create an instance and initialise with:
TFT myDisplay = TFT(CS, DC, RST);

myDisplay.begin();

Using GFX
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>

With the following #defines:
#define CS 10
#define DC 9
#define RST 8

Note: if you used different pins, then just change the numbers.
Create instance1:
Adafruit_ST7735 myDisplay = Adafruit_ST7735(CS,  DC, RST);

Initialise with
myDisplay.initR(INITR_BLACKTAB);

Further reading

Beginner Arduino - Using a 1.8 Inch TFT Display
Guide to 1.8 TFT Display with Arduino

Footnote
1
Alternative instance creation, which is slower, but you can use different MOSI/SCLK pins (hence the additional #defines):
#define SCLK 13   // You can change this
#define MOSI 11   // You can change this
Adafruit_ST7735 myDisplay = Adafruit_ST7735(CS, DC, MOSI, SCLK, RST);


text:
KIE-TS-300B turbidity sensor not working
I'm working with a clone Arduino micro board. I've got the color sensor up and running fine. So the problem isn't the card.
I'm using the example code, just to try out the module:
        // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // print out the value you read:
      Serial.println(sensorValue);
      delay(1);  // delay in between reads for stability
    }

A0 is on the output, ground and 5V wires are setup right. The red light on the module is red. I'm getting readings about 200-ish. That's about 1.5 V, if I convert it. I can't block it with an opaque object, that doesn't change the readings. I removed the cover, to see if it helps, still the same. I've tried three different sensors.
The one I'm using is this device: TS-300B Turbidity sensor water turbidity module turbidity detection module.
Any suggestions as to how, and why, is this happening?


text:
Arduino_DebugUtils.h: No such file or directory
How to get rid of this error?
/storage/emulated/0/ArduinoDroid/userlibraries/Arduino_ConnectionHandler/src/Arduino_ConnectionHandler.h:26:34: fatal error: Arduino_DebugUtils.h: No such file or directory

You need to install the Arduino_DebugUtils library.
From Arduino_DebugUtils:

To use this library, open the Library Manager in the Arduino IDE and install it from there.


text:
LED will fade in but not fade out
The brightness of the LED gets higher normally but when it gets to full brightness it just stays like that - it doesn't dim. Sorry if this has already been answered I just can't seem to find anything about this exact problem online. I have also tried a few different codes from tutorials but the outcome is the same.
int led = 6;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  for (int i  = 5; i <= 255; i+=1){
    analogWrite(led, i);
    delay(100);
  }

  for (int i = 255; i >= 5; i-=1) {
    analogWrite(led, i);
    delay(100);
  }
}

tip: i++ looks neater for increments of 1

Try the exact built-in fading code of the Arduino IDE instead.

Well, provided that you hooked up the led to the right pin, it actually does.
The point is human sight is quite imperfect. When light source becomes too bright we stop seeing shades. Also, we can see better the shades of green, rather than red or blue.
So you count from 5, skipping "the darkest values", with all even delays, and, probably, with the smallest resistor value possible. Then the led's brightness soon reaches the threshold and stays too high for the most of the time. You have only few seconds out of fifty to note that it dimmed a bit and then it becomes a bright spot again.
Instead, try using uneven delays, so lower values stay longer in effect and, maybe, increase current limiting resistor value and/or limit the values passed to analogWrite (e.g. up to 200 only).

It worked for me but it's slow. 251 iterations (of each loop) at 0.1 sec/loop takes 25 seconds up and 25 seconds down. When I reduced the delay to 10msec, the behavior was much more obvious.