text:
Compilation Error: "cannot declare 'client' to be of abstract type 'Client'"
I know, it isn't my original code, but I'm using this for a larger project that I am currently working on. I keep getting this error message: "cannot declare 'client' to be of abstract type 'Client'".
here's the code:

// RoboSapienServer.cpp
// RobosapienServer - Web enable a RoboSapien
// Kevin N. Haw
// http://www.KevinHaw.com/RoboSapienServer.php

// This project combines the default webserver example in the IDE distribution and Karl Castleton's(http://home.mesastate.edu/~kcastlet) RoboSapienIR (http://playground.arduino.cc/Main/RoboSapienIR).
// Source code merged from those two sources.

// Include files
#include <Ethernet.h>
#include <string.h>
#include <WebServer.h>

//////////////////////////////////////////////////////////////////
// Begin Web Server specific variable deinitions
//////////////////////////////////////////////////////////////////

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// KNH, 02/09/2010 - Change IP address to use local subnet at home
//byte ip[] = { 10, 0, 0, 177 };
byte ip[] = { 192, 168, 1, 177 };

// Server for web requests
EthernetServer server(80);

// Define field name in the submitted form
#define SUBMIT_BUTTON_FIELDNAME "RSCmd"

// String for HTTP request variables
char pcHttpReqRsCmd[20] = {'\0'};

volatile int viRobsapienUrlCmd = -1;  // A robosapien command sent over the URL of a webpage HTTP request

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific variable deinitions
//////////////////////////////////////////////////////////////////

// Some but not all RS commands are defined
#define RSTurnRight       0x80
#define RSRightArmUp      0x81
#define RSRightArmOut     0x82
#define RSTiltBodyRight   0x83
#define RSRightArmDown    0x84
#define RSRightArmIn      0x85
#define RSWalkForward     0x86
#define RSWalkBackward    0x87
#define RSTurnLeft        0x88
#define RSLeftArmUp       0x89
#define RSLeftArmOut      0x8A
#define RSTiltBodyLeft    0x8B
#define RSLeftArmDown     0x8C
#define RSLeftArmIn       0x8D
#define RSStop            0x8E
#define RSWakeUp          0xB1
#define RSBurp            0xC2
#define RSRightHandStrike 0xC0
#define RSNoOp            0xEF

// Subset of additional codes pulled from http://www.contrib.andrew.cmu.edu/~ebuehl/robosapien-lirc/ir_codes.htm
#define RSRightHandSweep  0xC1
#define RSRightHandStrike2 0xC3
#define RSHigh5           0xC4
#define RSFart            0xC7
#define RSLeftHandStrike  0xC8
#define RSLeftHandSweep  0xC9

#define RSWhistle         0xCA
#define RSRoar            0xCE

int IRIn = 2;            // We will use an interrupt
int IROut = 3;           // Where the echoed command will be sent from

boolean RSEcho = true;    // Should Arduino Echo RS commands
boolean RSUsed = true;    // Has the last command been used
volatile int RSBit = 9;   // Total bits of data
volatile int RSCommand;   // Single byte command from IR
int bitTime = 516;        // Bit time (Theoretically 833 but 516)
// works for transmission and is faster
int last;                 // Previous command from IR

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific code
//////////////////////////////////////////////////////////////////

// Receive a bit at a time.
//  NOTE: Unused in the RoboServer aplication
void RSReadCommand() {
  delayMicroseconds(833 + 208); // about 1 1/4 bit times
  int bit = digitalRead(IRIn);
  if (RSBit == 9) { // Must be start of new command
    RSCommand = 0;
    RSBit = 0;
    RSUsed = true;
  }
  if (RSBit < 8) {
    RSCommand <<= 1;
    RSCommand |= bit;
  }
  RSBit++;
  if (RSBit == 9) RSUsed = false;
}

// send the whole 8 bits
void RSSendCommand(int command) {
  digitalWrite(IROut, LOW);
  delayMicroseconds(8 * bitTime);
  for (int i = 0; i < 8; i++) {
    digitalWrite(IROut, HIGH);
    delayMicroseconds(bitTime);
    if ((command & 128) != 0) delayMicroseconds(3 * bitTime);
    digitalWrite(IROut, LOW);
    delayMicroseconds(bitTime);
    command <<= 1;
  }
  digitalWrite(IROut, HIGH);
  delay(250); // Give a 1/4 sec before next
}

// Set up RoboSpapien functionality
void RSSetup()
{
  pinMode(IRIn, INPUT);
  pinMode(IROut, OUTPUT);
  pinMode(10, OUTPUT);
  digitalWrite(IROut, HIGH);

  attachInterrupt(0, RSReadCommand, RISING);

  last = RSNoOp;

  // Make robot burp to indicate setup is complete
  RSSendCommand(RSBurp);

}

// Loop for RoboSapien functionality
// Write only functionality - send the command from the web page to the robot, ignoring any input from the remote
void RSLoop()
{
  // Has a new command come in from the server?
  if (viRobsapienUrlCmd != -1)
  {
    // New command - send it to robot
    Serial.print("Sending command to RoboSapien: ");
    Serial.println(viRobsapienUrlCmd, HEX);
    RSSendCommand(viRobsapienUrlCmd);

    // Now clear command
    viRobsapienUrlCmd = -1;
  }
}

//////////////////////////////////////////////////////////////////
// Begin Webserver Specific Code
//////////////////////////////////////////////////////////////////

// Print ourt MIME and HTML header at top of webpage
void HtmlHeader(Client client)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("\n");
  client.println("  <TITLE>Kevin's Arduino Webserver</TITLE>");//
  //  client.println("  <META HTTP-EQUIV=\"refresh\" CONTENT=\"5\">");
  client.println("");
}

// Print the footer at the bottom of the webpage
void HtmlFooter(Client client)
{
  client.println("");
}

// Print a submit button with the indicated label wrapped in a form for the indicated hex command
void SubmitButton(Client &client, char *pcLabel, int iCmd)
{
  client.print("<form method=post action=\"/?");
  client.print(iCmd, HEX);
  client.print("\"><input type=submit value=\"");
  client.print(pcLabel);
  client.print("\" name=\"" SUBMIT_BUTTON_FIELDNAME "\">");
  client.println("</form>");
}

// Parse an HTTP request header one character at a time, seeking string variables
void ParseHttpHeader(Client &client)
{
  char c;

  // Skip through until we hit a question mark (first one)
  while ((c = client.read()) != '?' && client.available())
  {
    // Debug - print data
    Serial.print(c);
  }

  // Are we here for a question mark or did we run out of data?
  if (client.available() > 2)
  {
    char pcUrlNum[3], *pc;

    // We have enough data for a hex number - read it
    for (int i = 0; i < 2; i++)
    {
      // Read and dump data to debug port
      Serial.print(c = pcUrlNum[i] = client.read());
    }
    // Null terminate string
    pcUrlNum[2] = '\0';

    // Get hex number
    viRobsapienUrlCmd = strtol(pcUrlNum, &pc, 0x10);
  }

  // Skip through and discard all remaining data
  while (client.available())
  {
    // Debug - print data
    Serial.print(c = client.read());
  }
}

// Set up webserver functionality
void WebServerSetup()
{
  Ethernet.begin(mac, ip);
  server.begin();
}

// Web server loop
void WebServerLoop()
{
  Client client = server.available();
  boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
  char c;  // For reading in HTTP request one character at a time

  if (client) {
    // Loop as long as there's a connection
    while (client.connected()) {
      // Do we have pending data (an HTTP request)?
      if (client.available()) {

        // Indicate we need to respond to the HTTP request as soon as we're done processing it
        bPendingHttpResponse = true;

        ParseHttpHeader(client);
      }
      else
      {
        // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
        if (bPendingHttpResponse)
        {
          // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
          bPendingHttpResponse = false;

          // send a standard http response header and HTML header
          HtmlHeader(client);

          // Put out a text header
          client.println("
Kevin's RoboSapien Webserver
");

          client.println("

");
          client.println("");

          // Create buttons
          SubmitButton(client, "WakeUp", RSWakeUp);
          SubmitButton(client, "Roar", RSRoar);
          SubmitButton(client, "Whistle", RSWhistle);
          SubmitButton(client, "High5", RSHigh5);
          client.println("
");

          client.println("	");

          SubmitButton(client, "LeftArmUp", RSLeftArmUp);
          SubmitButton(client, "LeftArmIn", RSLeftArmIn);
          SubmitButton(client, "LeftArmOut", RSLeftArmOut);
          SubmitButton(client, "LeftArmDown", RSLeftArmDown);
          SubmitButton(client, "LeftArmSweep", RSLeftHandSweep);
          client.println("
");

          client.println("	");

          SubmitButton(client, "RightArmUp", RSRightArmUp);
          SubmitButton(client, "RightArmIn", RSRightArmIn);
          SubmitButton(client, "RightArmOut", RSRightArmOut);
          SubmitButton(client, "RightArmDown", RSRightArmDown);
          SubmitButton(client, "RightArmSweep", RSRightHandSweep);
          client.println("
");

          client.println("

");

          client.print("

URL Hex no: ");
          client.print(viRobsapienUrlCmd, HEX);
          client.println("
");

          // send HTML footer
          HtmlFooter(client);

          // give the web browser time to receive the data
          delay(1);
          client.stop();
        }
      }
    }  // End while(connected)
  }
}

//////////////////////////////////////////////////////////////////
// Begin arduino entry points
//////////////////////////////////////////////////////////////////

void setup()
{
  // open the serial port at 9600 bps:
  Serial.begin(9600);

  // Print greeting
  Serial.println("Kevin's RobSapien Server");

  RSSetup();
  WebServerSetup();
}

void loop()
{
  RSLoop();
  WebServerLoop();
}

You can't use Client directly like that.  It's just an abstract class.  You have to use one of the classes like EthernetClient or WiFiClient that implements it.
Client is like a shell of a class.  It says that there will be classes that act as clients and will have this basic form.  But it doesn't have any code, just the outline.  The base classes that implement that abstract class like EthernetClient or WiFiClient actually have the code to actually BE a client.

I would guess the problem lies here:
void HtmlFooter(Client client) {
    client.println("");
}

(Also the HtmlHeader function)
When you call that function you make a new Client object and copy the contents of your existing object into it. Since Client is pure virtual you can't do that. Instead you should be working with a reference as in the other functions:
void HtmlFooter(Client &client) {
    client.println("");
}


text:
PS2 Keyboard and sending keystrokes between a Leonardo and several pro micros
I am working on a project where I am taking the the key presses from a PS/2 keyboard and passing them to several pro micro boards so I can type the same commands on multiple computers at the same time. I have a master board that is a Leonardo that is connected to a keyboard. Using the TX pin I am connecting to a pro micro and trying to receive keystrokes on the micro and output them to a computer. I can get a the keyboard to work with the Leonardo connected to computer but not the pro micro. What do I have wrong about communication between these devices.(I get maybe every other key correctly on the computer but a also other keys or even function keys.)  Code for the "Master":

#include <PS2Keyboard.h>
#include <Keyboard.h>

const int DataPin = 8;
const int IRQpin =  3;

PS2Keyboard keyboard;

void setup() {
  delay(1000);
  keyboard.begin(DataPin, IRQpin);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial.println("Keyboard Test:");
}

void loop() {
  if (keyboard.available()) {

    // read the next key
    char c = keyboard.read();

    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else if (c == PS2_F1) {
      Serial.print("[F1]");
      //Serial1.print("[F1 ]");
    } else {

      // otherwise, just print all normal characters
      Serial1.print(c);
    }
  }
}

Code for the "Slave":
#include <HID.h>
#include <Keyboard.h>

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

void loop(){
   if (Serial1.available() > 0) {
   // read incoming serial data:
   char c = Serial1.read();
   Keyboard.print(c);
  }
}

Could you try to use Serial1.write with a fixed byte. For example remove the Serial1.print(c); and before or after char c = keyboard.read(); a Serial1.write('H');

Interesting, I actually tried Serial1.write but where my keyboard.print(c) was located, but that actually is kind of making sense. I thought I needed to convert the data to a byte instead of a Serial1.print. No changes are necessary on the slave device correct?

Correct for normal characters, like 'a', 'b', 'A', 'B', '?'. The PS2 library returns those normal ASCII characters, they are transmitted over the serial line and send to the computer. Everything as normal ASCII characters. You need to translate the function-keys and other special keys. Is this good enough for you ? Or do you need to simulated a key being pressed for a long time and also the Alt, Ctrl and media keys as well ?

I am going to need to use the alt, Ctrl and function keys as well. I was hoping to get the regular keys working first as it seemed that special or modifier keys might be more difficult. The PS2Keyboard.h file is missing the bits for the function keys but I was able to get those working and I found the if else statements in an example to test the functions keys. What would be the best way to go about this?

Instead of the if-else-statements you can use a table. However, nothing is wrong with the if-else-statements. Try to make it work with the Arduino Keyboard library. Perhaps you have to detect the pressing down and releasing a key as two seperate events. To create a keyboard that can do everything, you might need https://github.com/NicoHood/HID/wiki If you are going to use that, start by reading about the three different types of keyboard. Perhaps the keyboard leds can be added as well, but I'm not sure of that. How is the problem going, can you get normal characters in the computers ?

I seem to be having the same issue with serial1.write.I put Serial1.write after keyboard.read and it spits out random keys. Here is an example if I hold down the k key: kkkJkkJk[JJJJkkkkJJkJk

Very strange, I don't know what could be the cause. Test every part one by one. For example the Micro running at its own sending keys. Does everything have enough voltage ? Could you try a different computer ?

source: Stack Exchange

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

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

sort: votes


text:
Why does I2C On Nano Fail with LiquidCrystal_I2C library unless Nano runs at 8Mhz?
I have an Arduino Nano (running by default at 16Mhz).
I am connecting a 20x4 LCD screen via I2C (using A4 for SDA and A5 for SCL).
Here's the very simple code (which was previously only showing black blocks on the screen -- but now seems to be showing odd chars).

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup() {
 lcd.begin();

  lcd.setCursor(2,0);
  lcd.print("test this");
}

void loop() {
  lcd.setCursor(5,2);
  lcd.print("Hello, world!");
}

ATmega328P DIP Circuit
I've been using this same LCD screen in another circuit which uses a raw ATMega382P (DIP) and it works 100% fine.
I put the LCD back into the circuit with the DIP, tested it and it works fine.
Then I remembered, that ATMega328P DIP runs at 8Mhz.
Run At 8Mhz
So that gave me the idea of running my Nano at 8Mhz just to see if it would work.
I altered the previous program just to set the CPU speed.  Here's the entire code again and a snapshot of it working.
#include <LiquidCrystal_I2C.h>
#include <avr/power.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup() {
   clock_prescale_set(clock_div_2);  // Sets to 8Mhz
 lcd.begin();

  lcd.setCursor(2,0);
  lcd.print("test this");
}

void loop() {
  lcd.setCursor(5,2);
  lcd.print("Hello, world!");
}

Questions
I've never changed anything on that LCD.
Is there something I'm missing?
I thought the SCL line (which is driven by the CPU) set the speed anyways??? -- -- and the LCD was just a slave.
Do you know of any reasons why this would behave this way?
Is there something I can change to run it at 16Mhz?

Can you print the value of the macro F_CPU on the serial monitor (or LCD)? Maybe the code (Wire.h) has compile-time checks for the clock speed and adjusts TWBRn wrong? (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf chapter 26.5.2)

As soon as I read your comment it flipped a switch on in my brain and I remembered what I have done. I feel a bit foolish.  I altered my boards.txt so it has this line : nano.build.f_cpu=8000000L  which is setting it to build for 8Mhz.  I was doing that because I use Arduino IDE to build HEX files for my ATmega328P DIP and then I use AVR Dude to flash them to my chip.  I'm running ATmega328P DIPs on internal 8Mhz.  Thanks very much, I wouldn't have remembered that I had altered that.

Wow, that was a quite a shot into the dark but I hit something :D. Doesn't the Arduino IDE have specific board variants for 8MHz and 16MHz variants which you could use? Anyways, I guess you can write your own answer to the question and accept it.

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


text:
How to program a CLK signal and its inverse with Arduino/AVR
Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?
I'm using the following code in arduino to output a 1MHz signal on OC1A:
//Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
//J.Christensen 27Apr2012

void setup(void)
{
    DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
    TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
    OCR1A = 7;                         //top value for counter
    TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
}

void loop(void)
{
}

How about this?
void setup()
  {
  // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
  // Setting DDB1 and DDB2
  DDRB |= bit (DDB1) | bit (DDB2);

  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                        // OC1B at BOTTOM (inverting mode)
         | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                        // OC1A at BOTTOM (non-inverting mode)
         | bit (WGM11);                 // Fast PWM, top at ICR1
  TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
         | bit (CS11);                  // Start timer, prescaler of 8

  // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
  ICR1 = 0xFFFF;
  OCR1B = 299;
  OCR1A = ICR1 - OCR1B;

  }  // end of setup

void loop()
  {
  }

Results on a Uno:

Output on Uno pins 9 and 10.
Change the prescalers and counters to your desired frequency.

The screenshot doesn't show one signal exactly the inverse of the other. The pattern is inverted. If you had a 50% duty cycle, it would be an exact inverse.

It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:
  ICR1 = 15;
  OCR1B = 7;
  OCR1A = 7;

Why 7? And why 15?
The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

Period: 16 ticks of the 16 MHz clock
Duty cycle: 8 ticks of the 16 MHz clock

Now, one cycle:

They change over at the same instant - pulse width exactly 500 ns.

And they change back at the same moment - pulse width also 500 ns.

Thanks! I was able to get a 1Mhz square wave by eliminating the prescaler and setting ICR1 = 15 and OCR1B = 7. It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical.

See amended reply for how to fix this.

Various AVRs have the capability to output both the normal and inverted timer waveform from a single output compare register simultaneously on two pins. These devices include, but are not limited to, ATtinyX5/V, ATtiny26/L, ATtinyX61A, and ATmegaXXU4.
The ATmega328P does not have this capability, therefore the smallest primary source Arduino that does is the Leonardo (ATmega32U4) and comparable devices. The Adafruit Trinket and the Digispark (both ATtiny85-based) also offer this.

Another option is to do this in hardware - it's trivial to invert a signal.
For example, see the selected answer for https://electronics.stackexchange.com/questions/30238/how-to-invert-a-digital-signal - the second diagram - connect Vs to your clock, and Vo will be your inverted clock. For the two resistors, anything over 1k should be fine. Or use an inverter (which is the same thing, in one component, but is much less likely to be in your random-part box).
Note: There will be a very short delay going through this circuit - one place I saw suggested 1.5ns, but see the spec sheet of your transistor. A 1mhz clock "ticks" at 1,000ns (I guess, 500ns on, 500ns off), so this delay shouldn't be significant.

Thanks, I originally tried to use an op amp to invert the signal and was surprised by how slow it was – it took about 10µs to switch. This probably would have been a faster, better approach, but if I can do everything in software that would be ideal.

This is out of my field of expertise a bit, but op-amps have a slew rate, which I believe means the time to change states. For example the LM158 is quoted as having 0.3 V/µs which means therefore to go from 0 to 5 V would take 5 / 0.3 = 16.66 µs, which is fairly close to your observations. You can get faster op-amps.

What about also setting COM1B0 and then setting the initial values of OC1A and OC1B to opposites by writing to PORTB?
Also, I presume you mean 1 MHz and not 1 mHz?

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


text:
Debouncing a limit switch in Arduino ISR with delays
I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.
As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.
const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
    pinMode(lsOuterLeftIn, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void  loop() {
    if (lsEngaged) digitalWrite(LED, HIGH);
    else digitalWrite(LED, LOW);
}
void ISR1(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}

But, here is my problem. I came upon this Arduino documentation page, and it says
"Since delay() requires interrupts to work, it will not work if called inside an ISR. "

But, I do make use of delay() inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the delay() function could malfunction on me as the documentation says?

What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.
Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.

Of course there are much nicer ways to deal with the problem, but they tend to be more complex (you could read about bottom halves, for example) than what you might be willing to spend time on.


text:
Connect ESP8266 ESP-12 with 2 arduinos
I understand how to connect one ESP-12 to an Arduino, but it's possible to make the ESP-12 connect to two arduinos? I found a lot of information about the gpio as txd-rdx but not at the inverse.
Is possible to connect pins 21 & 22 to one arduino and 7 & 16 to another one? What condiderations must I have to?

You can use softserial and use any io pins to connect the two arduinos via serial.

What advantage would sharing give you?  Is it worth the hassle?  I can't think of a reason why it isn't possible.


text:
Serial Monitor Stops Working
I am using a DIY colour sensor (RGB LED and LDR) and a servo to make a skittles sorter. I am testing out just the colour detection now and printing the RGB values to serial. It worked fine until I added servo code. Now it stops printing to serial after about 4 cycles. Not sure why this is happening. I have tried using other programs besides using the Arduino IDE but the same issue.
I am using a NodeMCU with Arduino code:

#define S0 4
#define S1 0
#define S2 2
#include <Servo.h>
Servo topServo;
int frequency = 0;

void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  topServo.attach(14);
 Serial.begin(9600);
 Serial.print("Start");
}

void loop() {
  topServo.write(125);
  delay(500);

  for(int i = 150; i > 80; i--) {
    topServo.write(i);
    delay(5);
  }
  checkcolours();
  delay(500);
}
void checkcolours(){
 //RED
digitalWrite(S1,LOW);
digitalWrite(S2,LOW);
digitalWrite(S0,HIGH);
frequency = analogRead(17);
int R = frequency;
Serial.print("R= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.print("  ");
delay(100);

//GREEN
digitalWrite(S0,LOW);
digitalWrite(S2,LOW);
digitalWrite(S1,HIGH);
frequency = analogRead(17);
int G = frequency;
Serial.print("G= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.print("  ");
delay(100);

//BLUE
digitalWrite(S0,LOW);
digitalWrite(S1,LOW);
digitalWrite(S2,HIGH);
frequency = analogRead(17);
int B = frequency;
Serial.print("B= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.println("  ");
delay(100);
returnservo();
  }
void returnservo(){
  topServo.write(30);
}

Are you sure you want to use pin 0 for S1? it seems that is the RX from the serial

Oh I didn't know that. It is actually pin D2 on the NodeMCU which maps to pin 0 for the Arduino IDE, could this be the issue?

I'm not sure, but I think it's very easy to change the number and change the wire for a small test

Great, ill check and let you know! Thank you so much :)

(I don't promise anything, just an idea, otherwise I would put it as answer)

It didn't work, i even tried swapping usb cables and used a different PC.

I'm sorry ... I hope someone else has a good answer

Isn't there a set of GPIOnn constants that you could use?  I have had a look and I can't see anything obvious with you code.  It might make it easier to see if you wrote a function change (int s0, int s1, s2, char* name) and move all the writing code into it, so you called that three times rather than replicating the code.  i.e. change(LOW, LOW, HIGH, "B= ");

I had tried your code in my nodemcu and it works fine. did you check the error log when serial stops printing?


text:
Scheduling and BLE Read on demand
I'm building a data logging device with BLE capability using RFduino.
Sensors are read using timer interrupt to a buffer. When the buffer is full, then the whole buffer is written to SD card.
At the same time, I have BLE_Receive to set time of the RTC clock on the device. Also BLE_send that transmit the current time of the necklace, and the freespace available (heartBeat or HB). Calculation of free space in particular might take a long time since it's IO operation.
Of course, reading sensors and writing data to SD card has highest priority, then transmitting heart beat only when the processor is free.

#include <Wire.h>
#include <Adafruit_VCNL4010.h>
#include <SPI.h>
#include <SdFat.h>
#include <TimeLib.h>
#include <RFduinoBLE.h>
#include "PCF8563RTC.h"

#define number_of_ms 100
#define NUM_SAMPLE_BUF    3        // number of data samples in buffer
#define SAMPLESIZEINCHAR 24        // verify at line 104, include null character
#define BUFLEN NUM_SAMPLE_BUF*SAMPLESIZEINCHAR + 1

volatile boolean connectFlag = false;
volatile boolean readSensorFlag = false;
volatile boolean heartBeatReadFlag = false;

// RTC variables
PCF8563RTC rtc;
tmElements_t tm;
time_t epoch;

// SD card variables
#define CHIPSELECT 2
SdFat SD;
File myFile;

// Proximity sensor
Adafruit_VCNL4010 vcnl;
uint16_t proximity;
uint16_t ambientLight;

// Double buffers to transfer data between sensors and SD card
char buffer[2][BUFLEN];
volatile uint16_t bufferCounter;
volatile int inBuf = 0;
volatile bool outBufHasData = false;

void timer_config(void) {
  NRF_TIMER2->TASKS_STOP = 1;  // Stop timer
  NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer;  // taken from Nordic dev zone
  NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit;
  NRF_TIMER2->PRESCALER = 9;  // 32us resolution
  NRF_TIMER2->TASKS_CLEAR = 1;  // Clear timer

  // With 32 us ticks, we need to multiply by 31.25 to get milliseconds
  NRF_TIMER2->CC[0] = number_of_ms * 31;
  NRF_TIMER2->CC[0] += number_of_ms / 4;

  NRF_TIMER2->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;
  NRF_TIMER2->SHORTS = (TIMER_SHORTS_COMPARE0_CLEAR_Enabled << TIMER_SHORTS_COMPARE0_CLEAR_Pos)
                        & TIMER_SHORTS_COMPARE0_CLEAR_Msk;

  attachInterrupt(TIMER2_IRQn, TIMER2_Interrupt);
  NRF_TIMER2->TASKS_START = 1;  // Start TIMER
}

void setup() {
  bufferCounter = 0;
  inBuf = 0;
  outBufHasData = false;

  // BLE stack
  RFduinoBLE.deviceName = "andrey";
  RFduinoBLE.begin();

  rtc.init();
  setSyncProvider(rtc.get);
  setSyncInterval(3600);

  // start SD card
  pinMode(CHIPSELECT, OUTPUT);
  if (!SD.begin(CHIPSELECT)) {
    return;
  }

  // Start sensors
  if (!vcnl.begin()) {
    return;
  }

  timer_config();
}

void loop() {
  // Reading data from sensors to a buffer
  if (readSensorFlag) {
    readSensorFlag = false;
    heartBeatReadFlag = true;

    if (bufferCounter < BUFLEN - SAMPLESIZEINCHAR + 1) {
      epoch = now();
      proximity = vcnl.readProximity();
      ambientLight = vcnl.readAmbient();

      // format to be fixed length as opposed to variable length
      // sacrifice overhead in written data with simpler and more robust code
      // since we know exactly how much to increment after each write
      int written = snprintf(&buffer[inBuf][bufferCounter], SAMPLESIZEINCHAR,
            "%10lu,%5d,%5d\n",
            epoch, proximity, ambientLight);

      if (written > 0) {
        bufferCounter += written;
      }
    } else {
      // only switch buffer if out buffer is written to SD card
      if (!outBufHasData) {
        inBuf = inBuf? 0:1;
        bufferCounter = 0;
        outBufHasData = true;
      }
    }
  }

  // write buffer to SD card
  if (outBufHasData) {
    // create folder if not exist
    char folderPath[3];
    snprintf(folderPath, sizeof(folderPath), "%02d", day());
    if (!SD.exists(folderPath)) {
      SD.mkdir(folderPath);
    }

    // Write buffer to SD card
    char filePath[19];
    snprintf(filePath, sizeof(filePath), "%02d/%02d%02d%02d%02d.csv",
        day(), month(), day(), hour(), minute());
    myFile = SD.open(filePath,  FILE_WRITE);
    if (myFile) {
      myFile.print(buffer[1 - inBuf]);
      myFile.close();
    }
    outBufHasData = false;
  } else {
    if (connectFlag && heartBeatReadFlag) {
        heartBeatReadFlag = false;
        transmitHeartBeat();
    }
  }
}

void transmitHeartBeat(void) {
  uint32_t heartBeat[8];
  heartBeat[0] = rtc.get();
  heartBeat[1] = SD.vol()->freeClusterCount() * SD.vol()->blocksPerCluster();
  RFduinoBLE.send((char*)&heartBeat, 8);

}

// read sensors periodically at 20Hz
void TIMER2_Interrupt(void) {
  if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
    NRF_TIMER2->EVENTS_COMPARE[0] = 0;
    readSensorFlag = true;
  }
}

void RFduinoBLE_onConnect() {
  connectFlag = true;
}

void RFduinoBLE_onDisconnect() {
  connectFlag = false;
}

void RFduinoBLE_onReceive(char* data, int len) {
  memcpy(&epoch, data, sizeof(time_t));
  rtc.set(epoch);
}

Currently my solution is as following: reading happens at the beginning of every interval of 100ms. Every 3 interval, the buffer is full and is written to SD card. During other 2 intervals, the processor is free thus I can get HB and transmit it.
Is there a better way? Could I have transmit HB on demand, i.e. transmit HB only when there's a request for it? How could I represent a request in Bluetooth LE? By setting a bit of BLE_receive?


text:
Convert to and from Unix Timestamp
What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE
I found some snippet of codes online, but have not tested it extensively yet.

  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:
unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib.
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').

+1 for TimeLib. I use it all the time for unix timestamps.

There is a standard way of doing those conversions in C, which is
through the functions defined in <time.h>. This API being standard,
you can test it in your computer. Recent versions of the avr-libc
support this: see time.h in avr-libc. These functions can handle
local time if you provide a function implementing the DST rules: see
set_dst(). Examples are provided for US and EU rules.

Awesome, I didn't know that the 'time.h' with timezone and also DST were included with the Arduino. Thanks. To connect a RTC chip with that time system is sadly not nice. Every second a system_tick() should be called. I just stay with the pjrc.com TimeLib for now.

@Jot That's not entirely correct. You can use a RTC to set the Arduino's internal clock, then call the internal clock for needed time info ... RTC in that case is merely a battery backed clock that is OCCASIONALLY used ... once per reboot and possibly every week or two for drift correction.

Here's an example to convert seconds (Unix time) to Date & Time using TimeLib.h:
#include <TimeLib.h>

unsigned long offset_days = 3;    // 3 days
unsigned long t_unix_date1, t_unix_date2;

void setup() {
  Serial.begin(115200);
  t_unix_date1 = 1564398600;
  Serial.print("t_unix_date1: ");
  Serial.println(t_unix_date1);
  offset_days = offset_days * 86400;    // convert number of days to seconds
  t_unix_date2 = 1564398600 + offset_days;
  Serial.print("t_unix_date2: ");
  Serial.println(t_unix_date2);
  printf("Date1: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date1), month(t_unix_date1), day(t_unix_date1), hour(t_unix_date1), minute(t_unix_date1), second(t_unix_date1));
  printf("Date2: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date2), month(t_unix_date2), day(t_unix_date2), hour(t_unix_date2), minute(t_unix_date2), second(t_unix_date2));
}

void loop() {

}


text:
Setting up Huzzah ESP8266
I am trying to set up a Huzzah ESP8266 and can not get it to work. I have scoured the internet for help and to no avail. I have the board loaded with a baud rate of 115200 and am transmitting at  80 MHz. When I try and upload the sketch it successfully uploads and after a second or two it sends me this error.

Sketch uses 222,209 bytes (21%) of program storage space. Maximum is
  1,044,464 bytes. Global variables use 31,576 bytes (38%) of dynamic
  memory, leaving 50,344 bytes for local variables. Maximum is 81,920
  bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Here is my code:
 void setup() {
pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
 void loop() {
digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the    voltage level
                                // but actually the LED is on; this is     because
                                // it is acive low on the ESP-01)
delay(1000);                      // Wait for a second
digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Does anyone know what I'm doing wrong or can anyone help me out.

Did you select the port of your ESP8266 in the Tools > Port menu? Please select File > Preferences > Show verbose output during > upload, upload the sketch, and then update the error message in your question with the full verbose output.

espcomm error messages usually mean that your sketch is -not- uploaded correctly. Are you sure you selected "Adafruit HUZZAH ESP8266" in the arduino IDE? It should be in the list.

Also, does the HUZZAH actually have a usb to serial chip on the board, or do you need an external one? If so whichone are you using? Some FTDI? I can't check myself atm., behind a firewall :)

Have you contacted your seller/supplier? Adafruit actually has very good support and they sure know their hardware and possible faults.

If you´re working with a development board, they (usually) come with tow buttons: Reset and Flash. If this is the case before start to upload your code you must press the Flash button, this error is common when the Flash button it's not pressed.
If you're working with an ESP8266-01 (this is the "naked" esp8266) you must read this tutorials: GreatScott vid on youtube, and for the connections: a good Hackster.io tutorial.
Hope you can make it run!!!

When using a serial cable (4 wires, only works on windows), you need to press the 2 buttons in the sequence described here (https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide): gpio0 down, reset down, reset up, gpio0 up. The red led should be dim now. This means the huzzah is ready to bootload.


text:
AD7606 DAQ and datalogging
I'm making a Data Acquisition System for force impact usign an AD7606 from Analog Devices, an Arduino DUE and a load cell. I already tested it following this guide an making the proper changes for Arduino DUE and some potentiometers for simulating the input signals. I can read variable 1-5 V signals pretty good but when I tried to read mV signals from my load cell I can't see any changes in the Visuino Scope. I've read some forums and using an amplifier is recommended. However, when I read the AD7606 datasheet it says that since it has a High Analog Input Impedance and Internal amplifiers, a previous  amplification phase isn't needed. Also, I want to avoid the noise from the external amplifiers.
I also tested my load cell using the HX711 ADC and it works fine, but I can't use it for my application because of its limited sampling frequency (80 Hz). AD7606 can give up to 200 kilo samples per second.
Does any one knows if I'm missing something for my input signal? if an amplifier is really nedded can you recommend me one?
Thanks

which load cell are you using and how is it connected?

It is a full Wheatstone Bridge made with 4 350 ohm straing gauges. 2 coils are fed.


text:
How to send chars and values at the same time from processing to Arduino
i have been trying to set Builtin LED frequency from arduino and turn it on and off .
I have created an interface with knobs and buttons in processing . I want to set delay between ON and OFF with 1 knob and OFF and ON delay with another knob . And button blinks the led at given frequency
In arduino i have tried something like this :
if(Serial.available() >0){
char val=Serial.read();
switch(val)
{
  case 'c':
  theValue=Serial.read();
  break;
  case 'd':
  theValue1=Serial.read();
  break;

case 'r':
digitalWrite(13,HIGH);
delay(theValue);
digitalWrite(13,LOW);
delay(theValue1);

break;
}

}

In the processing :
  public void Blink(){
   myPort.write('r');
 }

 public void knobON(int theValue){
   myPort.write('c');
   myPort.write(theValue);
 }

 public void knobOFF(int theValue1){
   myPort.write('d');
   myPort.write(theValue1);
 }

Can you help me on what should i do ?

Do you really need to read char over serial?  Why not send an number, i.e. integer?

The Arduino code sample you've provided is incomplete, and does not compile. On the Processing side, I would combine the LED On time with the Off time, using a separator, then ending with a \n. Something like this: myPort.write("1000:2000\n");.
There are many ways to parse the serial data into unsigned long to be used in the delay() function. Here is a sketch illustrating one way to parse it. I am using the serial monitor to send the following test data 1000:2000 (LED on for 1 second, off for 2 seconds). The serial monitor is sending the \n character.
char buffer[16];
unsigned long onTime;
unsigned long offTime;

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

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', buffer, 13);

    char * pch;
    pch = strtok(buffer, ":");
    onTime = strtol(pch, &pch, 10);
    pch = strtok(NULL, ":");
    offTime = strtol(pch, NULL, 10);

    digitalWrite(13, HIGH);
    delay(onTime);
    digitalWrite(13, LOW);
    delay(offTime);
    memset(buffer, 0, sizeof(buffer));
  }
}


text:
Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)
I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128.  When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.
I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.
Here's some explanations for implementing PID in Arduino.
http://playground.arduino.cc/Code/PIDLibraryConstructor
For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.
If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.
void loop()
{

  int pwmSpeed;

  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

  if (Y_axis == 128)
  {

    Setpoint = encoder0Pos;
    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

}

Thanks.
//New edited code is shown below:
What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.
If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.
However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.
global g_detect128 = false;

void setup()
    {
//any code here
    }

void loop()
{

  int pwmSpeed;
  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

 if (!g_detect128 && Y_axis == 128)
    {
    Setpoint = encoder0Pos;
    g_detect128 = true;
    }

  if (Y_axis == 128)
  {

    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

 if(Y_axis != 128)
    {
    g_detect128 = false;
    }

}

Why was this question migrated here? It seems like a pure programming problem. It should be sent to StackOverflow where I feel confident they would know how to respond to it.

@NickGammon Also, it already had a (correct) answer. Why bounce it all over Stack Exchange?

I apologize if this is sent to the wrong section. If I have further question, should I proceed here or should I post at stackoverflow?

@goddar If it's pure programming, StackOverflow. If it's something particular to do with Arduino (hardware or software), post here. If it's general electronics/circuit related, then post on EE.

If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:
boolean g_bSeen128 = false;

void setup()
{
    // ... whatever
}

void loop()
{
    // ... your existing code

    // catch first time we see 128
    if (!g_bSeen128 && Y_axis == 128)
    {
        // ... do whatever you need here. e.g.
        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

        // stop the event being caught next time
        g_bSeen128 = true;
    }

    // from comments below - to just ignore consecutive 128's, add this:
    if (Y_axis != 128) g_bSeen128 = false;

    // ... your existing code

}

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:
int g_nLastInput = -1;

void setup()
{
    // ... whatever
}

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change, e.g.
        if (Y_axis == 128)
        {
            // ... do something special for 128
        }
        else
        {
            // ... do something else for other inputs
        }
    }
}

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.
If that's correct, an alternative way of coding your original logic might be like this:
void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    Input = encoder0Pos;

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change
        int nDelta = Y_axis - 128;

        if (nDelta == 0)
        {
            // i.e. Y_axis is 128
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);
        }
        else
        {
            // choose direction
            digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

            // set PWM speed scaled to 0..255
            analogWrite(pwm, abs(nDelta) * 2);
        }
    }
}

Thanks Roger. That answers my question above. I think the way I program it is wrong.  What I really want is to record the encoder value as the Setpoint whenever it encounter the first value of 128 at any time during the operation. Then I want to feed that Setpoint (intended stop position) and the Input(current encoder position) to the Pid.compute() so that it will hold its position at the Setpoint. For example, if the readings are 130, [128], 128, 128, 140, 132, [128], 128. What if initially the joystick moves the motor, brake, then move again and then brake?

@goddar Ok, then after the if that I showed you, you just need to add if (Y-axis != 128) g_bSeen128 = false; So that will ignore consecutive 128's but will pick up new instances. I've updated the answer.

goddar, what should happen in that 130, [128], 128, 128, 140, 132, [128], 128 sequence?  Should the encoder be read twice, after 130 and after 132?  Or just once, after 130?

In the example, I would like to read the encoder value whenever arduino receive 128. I highlighted the ones I need to read with the square bracket, [ ] . So it will read twice in that example, first reading is at 1[28] after 130 and 2nd reading is after 132. What is your concern jwpat7? May I know?

Hi Roger or anyone else, how about other methods to achieve the what I want in my question above? This is for my knowledge since we're already discussing this topic.

@goddar I've just expanded my answer so you can see how to filter out all duplicate readings, so you only respond to a change of input. If you then want to do something different for a particular input, say 128, you can just test for that value inside the outer if condition.

Hi Roger, based on your latest code, thats indeed a better way to program it. Ive never thought of that. The goal is for my robot to follow my joystick and its signal will determine how fast my robot moves uphill or downhill. Then whenever I release my joystick, it will outputs value of 128. All the while when my arduino reads 128, I want it to hold its position/brake. This is when arduino will continuously execute the pid.compute (). This will go on until I move my joystick again to move the robot again. It seems that the code will execute the pid.compute () only when it encounter the first 1

Continued from above...it seems that the code will execute pid.compute () only when it encounters the first 128. Is there a way for it to execute the pid.compute () the whole duration when arduino sees 128?

Roger, I typed out the new code above based on your suggestion earlier. The description on how I intend it to work is stated above the new code. Could you please have a look? I'd like to hear your opinion whether it will work according to my description.


text:
GPS speedometer with NEO 6M - latency issue
I have built a speedometer, based on this
youtube video: https://www.youtube.com/watch?v=gKuJxjxNP-k&t=34s
The speedometer is for a car, so it needs to be in real-time and accurate, with the actual speed that the car reads. The speedometer is built with a NEO-6m GPS module with an antenna. It is hooked up to an Arduino Nano and an OLED 0.96".
This is the code and wiring diagram. The code is the same as the video and uses TinyGps library. But simplified to just show me the current speed(kmh). I have removed every other line of code, to reduce latency.

#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

#include <SoftwareSerial.h>
#define rxPin 2
#define txPin 3 //unused
SoftwareSerial neogps(rxPin,txPin);

#include <TinyGPS++.h> //1.0.3
TinyGPSPlus gps;
//---------------------------------------------------------------------------
int x_max    = 128;       //OLED display width, in pixels
int y_max    = 62;        //OLED display width, in pixels
int x_center = x_max/2;
int y_center = y_max/2+10;
int speed;
int adjspeed;// Adjusted speed for oversetimation by car
int num_sat;

//satellite logo
#define sat_logo_width 20
#define sat_logo_height 20

const unsigned char sat_logo[] = {
  0x00, 0x01, 0x00, 0x80, 0x07, 0x00, 0xc0, 0x06, 0x00, 0x60, 0x30, 0x00,
  0x60, 0x78, 0x00, 0xc0, 0xfc, 0x00, 0x00, 0xfe, 0x01, 0x00, 0xff, 0x01,
  0x80, 0xff, 0x00, 0xc0, 0x7f, 0x06, 0xc0, 0x3f, 0x06, 0x80, 0x1f, 0x0c,
  0x80, 0x4f, 0x06, 0x19, 0xc6, 0x03, 0x1b, 0x80, 0x01, 0x73, 0x00, 0x00,
  0x66, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x70, 0x00, 0x00
};
//---------------------------------------------------------------------------

//Program variables
double lat;
double lng;

void gauge() {

  //TOP LEFT: draw satellite logo and number of satellites
  u8g.drawXBM(0, 0, sat_logo_width, sat_logo_height, sat_logo);
  u8g.setPrintPos(18, 5);
  u8g.print(num_sat, 5);

  //---------------------------------------------------------------------------
  // Show Speed and align its position
  u8g.setFont(u8g_font_profont22);
  u8g.setPrintPos(54,60);

  if (adjspeed>99) {
    u8g.setPrintPos(47,60);
  }

  u8g.print(adjspeed);
  //---------------------------------------------------------------------------
}

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

  neogps.begin(9600);

  u8g.setFont(u8g_font_chikita);
  u8g.setColorIndex(1);
}

void loop(void){

  Read_GPS();

  //Display Data on Oled
  {
    u8g.firstPage();
    do {
      gauge();
    }
    while( u8g.nextPage() );
  }

}

void Read_GPS(){

  boolean newData = false;

for (unsigned long start = millis(); millis() - start < 100;)
  {
    while (neogps.available())
    {
      if (gps.encode(neogps.read()))
      {
        newData = true;
        break;
      }
    }
  }

  //If newData is true
  if(newData == true){
    newData = false;
    Get_GPS();
  }
  else {
    //no data
  }
}

void Get_GPS(){
  num_sat = gps.satellites.value();

  if (gps.location.isValid() == 1) {
    speed = gps.speed.kmph();
    adjspeed = 1.03*speed; // the speed is adjusted(increaed) to match the speed that the actuall car outputs. (Because there is a law stating that cars need to overestimate the actual speed by a little bit
    Serial.print("Speed: ");
    Serial.println(adjspeed);

  }
}

The speedometer is accurate and shows the right speed, but there is a latency of around 1-2 seconds. For example, if the car starts accelerating from 0, the OLED shows the speed 1-2 seconds later, the same with when the car brakes. I need the latency to be, at least, less than a second.
I'm a bit of a beginner and not sure how to reduce this latency. I was hoping for someone here to explain to me how I can reduce this latency

what's the purpose of the for statement in Read_GPS()?

reduce your program to minimum code that reads raw GPS data and dumps it to serial port

Which NMEA messages do you expect? You seem to be trying to process all messages, but then abort on the first one you get.

By default, the Neo 6M (if it's a genuine U-blox) outputs 1 position update per second but it can be set to a maximum of 5 position updates per second (5 Hz) which will reduce the latency. If you decide to change the update frequency, you should also increase its baud rate. You can use U-Blox's u-center software to change these settings.


text:
How would I link inline debugger with esp32 on Mac?
I am trying to connect JTAG debugger to my esp32 according to the following steps https://www.instructables.com/How-to-Use-a-Debugger-on-an-ESP32/
but still I am facing issue in debugging. I am working with MAC
below is the error I am facing while debugging
No dependencies
Building in debug mode
Checking size .pio/build/uno/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.5% (used 1118 bytes from 32256 bytes)
Configuring upload protocol...
AVAILABLE: arduino
CURRENT: upload_protocol = arduino
Looking for upload port...
Auto-detected: /dev/cu.usbserial-1201
Uploading .pio/build/uno/firmware.hex
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

*** [upload] Error 1

You have built for (and are attempting to upload to) an Arduino UNO not an ESP32.


text:
How arduino PORTB pins are addressed if I want to access them with pointer?
So Let say I want to access Digital Pin 13. Thats port B pin. Is there an memory address associated with this pin 13 of Arduino Uno r3?
How Port B pins are addressed with corresponding pin numbers like What is the address of digital pin 13?
Currently I am assuming its pin address is 0x05 so my pointer looks like this
    uint8_t *adr=0x00+0x05;

Now If I do
  *adr |= 0x20;

then should I expect that I am writing to some pin so I like to know which data sheet I should refer for pin addresses of port B?
Currently my code is not working because no matter which pin I connect my LED to it blinks. What if I dont want to use any library and just write to address and I need PORT B pin address how to refer to different pins?
Now assume I have a code that uses avr gcc
#include <avr/iom328p.h>//avr/io.h
#include    <util/delay.h>
#include <avr/sfr_defs.h>

#define     BLINK_DELAY_MS  18000

int main (void)
{
    DDRB |= _BV(DDB5);

    while(1)
    {
        PORTB |= _BV(PORTB5);
        _delay_ms(BLINK_DELAY_MS);

        PORTB &= ~_BV(PORTB5);
        _delay_ms(BLINK_DELAY_MS);
    }

    return 0;
}

What is the values correspond to DDRB and _BV(DDB5); and PORTB and _BV(PORTB5);? I like to do it with pointers so I need addresses of PORT B all pins I know the macros but I like the actual addresses . there should be a some datasheet for this what  its called. Does arduino has it that gives memory mapped addresses?
The above code is simply for blinking LED light

What did you find when you looked into the included header files? What did you find when you read the documentation of avr-libc? What did you find when you looked into the Mega128 data sheet? Why did this not help you?

@thebusybee what not making sense to me is this PORTB |= _BV(PORTB5) and DDRB |= _BV(DDB5); why PORTB generic address is used and what the hell is DDRB |= _BV(DDB5);  where is the documentation on this memory mapped io. This is simple question. I checked gcc avr it's has addresses. But shouldn't  there be some description for these macros and addresses. It's must be in data sheet but wait what I actually found was tuns of pages about pin layouts when search for arduino uno r3 datasheet.

That's why this question. It should have been pretty simple for what I am looking for but seems like there is lack of info. I need explanation

Exercise your web search skills and look for "atmega128p data sheet" and "avr-libc". You might need to read and think a bit, not everything in the real world is answered right away in the first link especially for you. We expect a bit of effort on your own.

I think your problem is some misconception about how are io pins handled. Port is for multiple io pins. One io port is handled with one bit of the port register.

The address of PORTB can be found in the ATmega328P datasheet,
section “I/O-Ports”, subsection “Register Description”. It is repeated
near the end of the section “Register Summary”, where it is documented
as:
0x05 (0x25)

Admittedly, this is confusing: there are two addresses! There is a
footnote that gives some hint on the reason:

When using the I/O specific commands IN and OUT, the I/O addresses
0x00 - 0x3F must be used. When addressing I/O Registers as data space
using LD and ST instructions, 0x20 must be added to these addresses.

To clarify, this register is mapped in two different address spaces:

It has I/O address 0x05. The I/O address space is a small (6 bits)
address space dedicated to I/O registers. It is actually too small to
host all the I/O registers. It can be accessed with the in and out
instructions. Addresses lower than 32 can also be bit-addressed with
the instructions sbi, cbi, sbis and sbic.

It has data address 0x25. This is a much larger address space that
gives access to all the I/O registers and to the RAM. It is used with
the ld/st family of instructions.

Since the C and C++ languages are not aware of the I/O address space, a
regular data pointer is assumed to always point to the data address
space. Thus, if you want to create a pointer to this register, you may
write:
volatile uint8_t *adr = 0x25;  // PORTB

Note the volatile qualifier. This is required to prevent the compiler
being too “smart” and optimizing out some of your writes under the
assumption that this is just RAM.
Then you may turn the LED on with:
*adr |= 1 << 5;  // set PORTB5

Withe the proper optimization options, the compiler may be able to
optimize this into sbi 0x05, 0x05, if it can prove that the address
stored in the pointer doesn't change.

I need addresses of PORT B all pins I know the macros but I like the
actual addresses.

I would recommend this:
volatile uint8_t *adr = &PORTB;

This avoids having magic numbers in your code, and makes the
programmer's intent clear.
One last comment. When compiling your code I got:
include/avr/iom328p.h: [...]
error "Include <avr/io.h> instead of this file."

Just include <avr/io.h>: this header takes care of including both the
correct <avr/iomXXX.h> and <avr/sfr_defs.h>.

I'd just dropped a comment about memory mapping the SBI part on the other answer. It's like having my mind read.

re: "if it can prove that the address stored in the pointer doesn't change": you can give it a hand by making the pointer const, e.g. volatile uint8_t * const adr


text:
Inheritance not working as expected
Short version: This is a lighting control project.  Some of the clases are Pin and  Channel. Channel contains a Pin.  Pin is a base class for DigitalOutPin and will be the base class for AnalogOutPin, and I want Channel to be able to use any child of Pin.
Pin has an abstract method setPinValue(), but when I create a DigitalOutPin object and call setPinValue(), Pin.setPinValue() gets called, not DigitalOutPin.setPinValue() and my program doesn't work because Pin.setPinValue() is empty as it's supposed to be overwritten.
Long version:
If I leave out the definition of Pin.setPinValue(), I get that most idiotic of error gcc messages, "undefined reference to `vtable for Pin'".  If I make it pure virtual I get several errors in the form of
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:21:20: error: cannot declare parameter 'pin' to be of abstract type 'Pin'
     void begin(Pin pin, int channelNumber);
                ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   because the following virtual functions are pure within 'Pin':
 class Pin
   ^
/devel/arduino/libraries/LightBrightLib/Pin.h:33:18: note:  virtual void Pin::setPinValue(int)
     virtual void setPinValue(int value)=0;
              ^
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:23:9: error: invalid abstract return type for member function 'Pin Channel::getPin()'
 Pin getPin();
     ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   since type 'Pin' has pure virtual functions
 class Pin
   ^

Full code is at GitHub but here are the relevant parts:
Pin is declared like this right now as pure virtual, but I've tried with and without =0
class Pin
{
  public:
   ...
  protected:
   ...
  // This method is child-specific. It's empty in this base class
  virtual void setPinValue(int value)=0;
};

DigitalOutPin is declared as
class DigitalOutPin : public Pin
{
  public:
    void on();
    void off();
  protected:
    void setPinValue(int value);
};

and defined as
void DigitalOutPin::setPinValue(int value) {
....
}

Disclaimer: I'm primarily a Java developer so C++ OO is very different for me, but as far as I can tell this should work as designed.
Thanks for any advice you can offer.

Your DigitalOutPin is protected - it should be public to match the base class definition and allow access outside the class.

Especially in embedded context, you might want to take advantage of final, which can enable the compiler to produce more efficient binary code: http://en.cppreference.com/w/cpp/language/final

From the same POV, if you can avoid having VMT and runtime lookup, it's definitely more efficient. One way to do that could be to turn is_a relationships into has_a ones.

@Majenko Sounds like that could be it! Originally I had another public method that called that one, and likely it broke then. I will try that tonight.

@IgorStoppa Very good suggestion. Thanks. Will chec out that link tonight.

@IgorStoppa WRT inheritance vs composition, I specifically want a Channel to hold any child of Pin, so that wouldn't work here, but good to know in other circumstances.  Thanks again.

@Majenko Actually rereading the code, I elided the protected: line when shortening the code above.  I just fixed that in the question.  It's protected in Pin and DigitalOutPin.  Sorry for leading you astray, but that's not the problem here.

I have taken your code from above and compiled it for a PC in Visual Studio.
When I create an object of type DigitalOutPin and call setPinValue() it calls the function I expect.  So this means either you have managed to find a bug in the gcc compiler, or there is something else in your code that is coming into play.  Can you try writing a VERY simple minimal test program that defines the Pin class and DigitalOutPin class (with just the setPinValue functions that print a string) and the setup and loop functions.  Just to see if you have found a gcc bug.
Even if this fixes the inheritance problem, you have other issues with you code because C++ is weird.  In Channel.h your Pin variables will need to be pointers, this will allow them to call the functions in the derived classes, not the base class functions.
I think you may get a performance improvement by using "const int& foo" for you parameters.  The const means the function can't change it, this allows the compiler to treat it differently and the "&" means use a reference to the variable rather than make a new copy of it.
Functions that don't change member variables within the code should also be declared constant.  "int FooBar(const int& value) const;"  It makes it clearer to the reader and the compiler probably does some funky stuff to improve performance.  (You might want to investigate "inline" if you are writing one line functions.)
Finally I'd recommend using constructors and destructors.  In release builds variables are not assigned a value.  If these variables are class members this means you don't know what they are to start with.  Also derived classes should initialise the base class, so:
// Class constructor for DigitalOutPin
DigitalOutPin::DigitalOutPin(const int& pinNumber)
  : Pin(pinNumber)  // Initialise the base class
  , m_State(false)  // Initialise all the class members (in order declared in .h file)
{
  // Lots of lovely code
}
// Class destructor for DigitalOutPin (Declared as virtual)
DigitalOutPin::~DigitalOutPin()
{}

Thank you Matt.  In doing more research I started to think the problem was that it wanted to instantiate Pin somewhere, and I came to the same conclusion that that Channel needed a *Pin not a Pin, and changed all the uses of it to dereference the pointer.  At that point it worked as expected.  I still need to make most of the parameters const references, but it's working now.  Thank you .

With respect to constructors and destructors, it's my understanding that constructors have very limited value in the Arduino world, and it's best to have a begin() method to initialize the object, because of the order things are initialized, what can happen in loop(), what can happen in setup(),...


text:
IR receiver transmitter High frequency
I build photo gate, to detect throwing ball.
It works fine when delay time in main loop for max 40 milliseconds.
Problems start when I delay every loop only for 20 milliseconds, now my LED which indicates if something broke path between IR led and IR receiver, blinks occasionally, if I set delay for 10 milliseconds and turn on, then LED is off for 2 seconds, then start blinking very fast and is ON for rest time, until I break IR path. I think some physics is going on here which I don't understand.
I also would like to ask if it is possible to narrow IR wave path to be more like laser (going strait into one direction) and how I can control sensitivity of IR detection
This is schematic
IR transmiter
IR reciever
Code:
//define pins. I used pins 4 and 5
#define irLedPin 4          // IR Led on this pin
#define irSensorPin 5       // IR sensor on this pin
#define buzzerPin 2       // buzzer on this pin

int irRead(int readPin, int triggerPin); //function prototype

void setup()
{
  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
  // prints title with ending line break
  Serial.println("Program Starting");
  // wait for the long string to be sent
  delay(100);
}

void loop()
{

  bool isOn = irRead(irSensorPin, irLedPin);
  //Serial.println(isOn); //display the results
  if(isOn == true)
  {
    digitalWrite(buzzerPin, HIGH);
  }
  else
  {
     digitalWrite(buzzerPin, LOW);
  }
  delay(10);
}

int irRead(int readPin, int triggerPin)
{
  int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds
  int cycles = 23; //26 microseconds * 23 is more or less 600 us
  int i;
  for (i=0; i <=cycles; i++)
  {
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(halfPeriod - 1);     // - 1 to make up for digitaWrite overhead
  }
  return digitalRead(readPin);
}

You can get IR laser diodes if you want a beam.

Or you can use red laser beam and use that as a IR source.

@Avamander, wow that's strange, I just checked and it works, but how? my red laser has 570 nm and IR reciver 950nm and it works, how ?

The laser has close enough wavelength, the same thing works with red LEDs too.

While you are doing a delay() you can't be doing anything else - that includes looking to see if the beam has been broken by the ball.
You must not use delay() in your sketch, instead use millis() as in the BlinkWithoutDelay example sketch in the IDE's File -> Examples menu.
Also how you are dealing with your IR system is incorrect.  You are first generating a brief square wave and then afterwards you are looking to see what was received.  Instead you need to be generating the square wave and at the same time see if that square wave is being received.  Normally that is achieved by using one of the PWM outputs of the Arduino set to the right frequency to generate a constant waveform which the receiver then senses all the time.


text:
Combine DHT22 and SI114X.h
It looks like I cannot combine the Grove sunlight sensor and the Grove DHT22 temperature and humidity sensor. I can't figure out why.
I have the following setup:

Seeeduino Cloud (Arduino Yún clone)
Grove Shield Grove sunlight sensor connected to an I2C port
Grove DHT22 temperature and humidity sensor connected to port A0

I'm sending the data to Initialstate.com. This is my code:

// Process.h gives us access to the Process class, which lets
// us communicate with the shell
#include "DHT.h" //Temp Hum sensor
#include <Bridge.h>
#include <Process.h>
#include <Wire.h>
#include "SI114X.h" //Sunlight sensor

SI114X SI1145 = SI114X();

////////////////////////////////////////////

//Temperature and Humidity sensor data start
#define DHTPIN A0
// what sensor is connected to, in this case A0
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);
//Temperature and Humidity sensor data end

////////////////////////////
// Initial State Streamer //
////////////////////////////
// URL to IS Bucket API
String ISBucketURL = "https://groker.initialstate.com/api/buckets";
// URL to IS Event API
String ISEventURL = "https://groker.initialstate.com/api/events";
// Access key (the one you find in your account settings):
String accessKey = "KRYLC3tvJUiyTVqTJr5nRqgkKQI2FiDh";
String bucketKey = "Test_Klimaat2";
// Bucket name (name your data will be associated with in Initial State):
String bucketName = "Test klimaat 2";
// Bucket key (hidden reference to your bucket that allows appending):
//String bucketKey = "arduino_stream";
// Bucket name (name your data will be associated with in Initial State):
//String bucketName = "Arduino Stream";
// How many signals are in your stream? You can have as few or as many as you want
const int NUM_SIGNALS = 5;
// What are the names of your signals (i.e. "Temperature", "Humidity", etc.)
String signalName[NUM_SIGNALS] = {"Humidity", "Temperatur", "Visable", "Infrared", "UV"};
// This array is to store our signal data later
String signalData[NUM_SIGNALS];

// This only runs once at the very beginning
void setup() {
  Serial.begin(9600);
  Bridge.begin();
  Wire.begin();
  SI1145.Begin();
  dht.begin(); //Initialize temparature and humidity sensor

  while (!Serial);
    // Post Bucket
    Serial.println("Posting Bucket!");
    // The postBucket() function creates a bucket
    // (unnecessary if the bucket already exists)
    postBucket();
}

// This repeats
void loop() {
  // Gather Data
  // Read from a port for input or output or generate your own values/messages
  // These signals are random numbers for the sake of example

  String VIS;
  String IR;
  String UV;
  String TEMP;
  String HUM;

  //Code reading DHT22
  HUM = String((float)dht.readHumidity());
  TEMP = String((float)dht.readTemperature());

  //code reading Sunlight data
  VIS = String(SI1145.ReadVisible());
  IR = String(SI1145.ReadIR());
  UV = String((float)SI1145.ReadUV()/100);

  signalData[0] = HUM;
  signalData[1] = TEMP;
  signalData[2] = VIS;
  signalData[3] = IR;
  signalData[4] = UV;

  // Post Data
  Serial.println("Posting Data!");
  // The postData() function streams our events
  postData();
  // Wait for 5 seconds before collecting and sending the next batch
  delay(5000);
}

// Here are the data bucket creation and posting functions
// They do not need to be edited - everything you would need to change for
// your situation can be found above

void postBucket() {
  // Initialize the process
  Process isbucket;

  isbucket.begin("curl");
  isbucket.addParameter("-k");
  isbucket.addParameter("-v");
  isbucket.addParameter("-X");
  isbucket.addParameter("POST");
  isbucket.addParameter("-H");
  isbucket.addParameter("Content-Type:application/json");
  isbucket.addParameter("-H");
  isbucket.addParameter("Accept-Version:0.0.1");

  // IS Access Key Header
  isbucket.addParameter("-H");
  isbucket.addParameter("X-IS-AccessKey:" + accessKey);

  // IS Bucket Key Header
  isbucket.addParameter("-d");
  isbucket.addParameter("{\"bucketKey\": \"" + bucketKey + "\", \"bucketName\": \"" + bucketName + "\"}");
  isbucket.addParameter("https://groker.initialstate.com/api/buckets");
  // Run the process
  isbucket.run();
  Serial.flush();
}

void postData() {
  // Initialize the process
  Process isstreamer;
  isstreamer.begin("curl");
  isstreamer.addParameter("-k");
  isstreamer.addParameter("-v");
  isstreamer.addParameter("-X");
  isstreamer.addParameter("POST");
  isstreamer.addParameter("-H");
  isstreamer.addParameter("Content-Type:application/json");
  isstreamer.addParameter("-H");
  isstreamer.addParameter("Accept-Version:0.0.1");

  // IS Access Key Header
  isstreamer.addParameter("-H");
  isstreamer.addParameter("X-IS-AccessKey:" + accessKey);

  // IS Bucket Key Header
  // Note that bucketName is not needed here
  isstreamer.addParameter("-H");
  isstreamer.addParameter("X-IS-BucketKey:" + bucketKey);

  isstreamer.addParameter("-d");

  // Initialize a string to hold our signal data
  String jsonData;
  jsonData = "[";
  for (int i=0; i<NUM_SIGNALS; i++) {
    jsonData += "{\"key\": \"" + signalName[i] + "\", \"value\": \"" + signalData[i] + "\"}";
    if (i != NUM_SIGNALS - 1) {
      jsonData += ",";
    }
  }
  jsonData += "]";
  isstreamer.addParameter(jsonData);
  isstreamer.addParameter("https://groker.initialstate.com/api/events");
  // Print posted data for debug
  Serial.print("Sending data: ");
  Serial.println(jsonData);
  // Run the process
  isstreamer.run();
  Serial.flush();
}

When I run this code, the Serial monitor will correctly display the data string I want to send with all values. However the data is NOT sent. Only when I comment out one of these lines in the loop() declaration the data is sent to Initialstate successfully. Obviously without the data commented out:
  //Code reading DHT22
  HUM = String((float)dht.readHumidity());
  TEMP = String((float)dht.readTemperature());

  //code reading Sunlight data
  VIS = String(SI1145.ReadVisible());
  IR = String(SI1145.ReadIR());
  UV = String((float)SI1145.ReadUV()/100);

Any ideas are appreciated.

Just a little question, are you getting accurate readings using the DHT22? What resistor value are you using?

The readings are accurate. I'm using the grove sensor so not resistor required (I assume) : https://www.seeedstudio.com/Grove-Temperature%26Humidity-Sensor-Pro-p-838.html.

I found the solution. Based on this post: http://forum.arduino.cc/index.php?topic=198433.0 I concluded that my strings are too long or my board runs out of memory. I removed the posting of the bucket and created abbreviations in my signal names. This solved the problem.


text:
How to allow cross-domain requests on ESP8266WebServer
I am using a Raspberry Pi running Chrome (handling the user interface) and connecting via ajax to an Arduino D1 compatible using the IP address as follows:
    $.ajax({
        type: "GET",
        url: "http://10.1.1.100/myfunc?id=5",
        error:  function(jqXHR, exception, response) {
                console.log(exception, response);

        etc...

I recently started getting this error (wonder why it didn't happen for the last two years):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.1.1.100/myfunc?n=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I tried various things including setting the browser (Chrome) to --disable-web-security and various suggestions, here and here (and many more) but I can't seem to get it to work. Currently, I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);

void handleRoot() {
  server.send(200, "text/plain", "Root of WebServer!");
}

void setup() {
IPAddress ip(10.1.1.100);
IPAddress gateway(10.1.1.1);
IPAddress subnet(...);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
  // put your setup code here, to run once:
  WiFi.begin(ssid, password);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  server.on("/", handleRoot);

  server.on("/myfunc", [](){
    String message = "";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";
    for (uint8_t i=0; i<server.args(); i++){
      message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
      String num = server.arg(0);

    server.send(200, "text/plain", message);
 });
  server.on("/myfunc", HTTP_OPTIONS, []() {
    server.sendHeader("Access-Control-Allow-Origin","*")
    server.send(204);
 });

  server.onNotFound(handleNotFound);
  server.begin();
}

void loop() {
  delay(1000);
  ...
  server.handleClient();
}

void handleNotFound(){
  String message = "Error!";
  server.send(404, "text/plain", message);
}

So what am I doing wrong? Also, one complication that might crop up later is that the domain from where I am calling this in ajax is https and from what I understand https and http are not compatible with cross-domain requests.
Any help is appreciated!

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Thanx @Majenko but that is too general and doesn't address the esp8266 scenario.

Does the page that is doing the Ajax request have the CORS headers?

add the CORS header to every response, not only for 'preflight' OPTIONS request. @Majenko, only resources ncluded from other server need CORS headers

you don't need the OPTIONS support, just add the ACAO header to the response

@Juraj and @ dandavis I combined both your comments and it now works!  I removed the OPTIONS part and put server.sendHeader("Access-Control-Allow-Origin","*"); in the response.  Thanx!  If either want to put it in the form of an answer I will be happy to accept it.

@dandavis - notifying you separately because SE only allows one user to be notified per comment

Add the CORS header to every response, not only for 'preflight' OPTIONS request. The OPTIONS support is optional, but the response returning the 'shared resource' must contain the CORS header
"Access-Control-Allow-Origin: *"
EDIT: since 2020, the library has server.enableCORS(true);

just add this line before every response:
server.sendHeader("Access-Control-Allow-Origin", "*");

server.enableCORS(true);

The server will add the response Access-Control-Allow-Origin=* header

enableCORS was added in 2020


text:
Using an Arduino board to program an AVR
I think the arduino board is awesome.
Though I'm not interested in the library and IDE at all...
Is there a way, to use an AVR 328p, as you normally would, on an arduino board?
I like how arduino's can be programmed through serial, can get powered through serial and I often use serial as a debugging option. Making my own board (with ICSP programmer) would not be able to do this (withouth bootloader).

The Question
Do I have to use all the stuff from arduino?

Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
Can I still program through serial then? (Does the bootloader care which compiler I used? Does Eclipse/AVR studio have the options to program through serial?)
Other stuff I should take in mind. (Annoying things like AVR studio not having a COM port window, though that's an easy fix.)

Edit: We've programmed an AVR 328P (GNU-GCC / Eclipse / ICSP) in school, so I know it takes quite some work to get the compiler set up, working with Eclipse. You don't have to completely describe the proces :) Just to avoid someone spending hours on an answer that's easily found on the internet.
(On my search for this subject I could only find people doing the other way around, getting an 328p chip to work with arduino)

Hope this helps. If my answer is insufficient, you can suggest me improvements for the comments.

FYI, the Arduino IDE works on top of avr-gcc, the GNU binutils and avrdude. The Arduino core library is built on top of avr-libc. If you wish, you can use the library without the IDE and vice-versa.

I actually didn't know that, sounds interesting.
I just don't want too much overhead. The bootloader is okay I think as it enables the serial uploading of code, which is great for my user experience.
But apart from that I try to make it as "professional" as possible, how people in real companies work. (Please don't take this as an 'insult').
I believe Eclipse is easier to use, but was worried it might not work as well with the arduino (uploading through serial). And personally I don't like it to use libraries (though I probably will for some things) but mostly from the chip manufacturer self.

Do I have to use all the stuff from arduino?

A = No!

Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
Can I still program through serial then? (Does the bootloader care which

Of Course! I use Eclipse IDE and I programming boards with Arduino bootloader directly in C/C++ using avr-gcc and avrdude.
Configuring Eclipse
First, let's download a plug-in for integrating AVR GCC and Avrdude + Eclipse IDE
To install the plug-in, point to the menu "Help> Install new software":

We will set a new location to download the plugin. Click the "Add ..." and type: AVR - Eclipse and the URL: http://avr-eclipse.sourceforge.net/updatesite

Now select the plugin that appeared in the list and click "Next":

Next, next, "I Acept the terms...", restart...
Now we install the plug-in, we will set it up. Point to the menu "Window> Preferences." Click in "AVRDUDE". The following screen:

On the next screen "AVR DUDE" let's set our recorder. Click "Add" to "Programmer configuration". Search for "Arduino".

Or, if you prefer, you can program making use of avr libraries in own Arduino IDE. Try to upload the following code into an Arduino board! While a blink costs almost 1,056 bytes of memory using an Arduino Uno, the following code uses only 164 bytes and does the same thing :)
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clr_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define tst_bit(Y,bit_x) (Y&(1<<bit_x))
#define cpl_bit(Y,bit_x) (Y^=(1<<bit_x))

#define LED PB5

int main( ){
    DDRB = 0xFF;

    while(1){
        cpl_bit(PORTB,LED);
        _delay_ms(200);
    }
}

If you use Linux, you can take a sudo cat/dev/ttyACM0 to detect what lies serial and echo "string" >> /dev/ttyACM0 to send data.

This is (I believe) exactly how we did it at school.
Though would this still enable me to program the arduino through the serial connection? Withouth an ICSP/USBasp programmer?

Yes, you can program it without a ICSP/USBasp programmer. Just change the recorder's type to "Arduino" on Eclipse IDE. I did not have another example of photo, in my photo is "USBasp" but just search for Arduino and exit programming. You can also use the Arduino IDE typing code directly in C ++. Test my example :) What is your Arduino board? Well, she must have a conversion circuit Serial/TTL. Sometimes is a ATmega8 sometimes one FTDI chip. (Sorry my english)

I've not yet bought an arduino board.
Though I think of going for an arduino nano breadboard (USB), one of those you can put on a breadboard.
They seem to have ICSP header also, but I think it's inconvenient to have 2 USB's going to your PC (one for serial and one for uploading code)
But if it's so that I can upload code through serial, this is/will be the answer?
(It was more towards a theoretical question, though you did really give in-depth explanation, might save me (and others) some time :D)

I recommend you buy an Arduino Uno. You can take the ATmega328P and put it on a breadboard and can write the bootloader in other chips (bootloader is a firmware header responsible for writing the code for serial). What about the upload, you'll use only one USB. When recording via ICSP is used SPI communication. But the Arduino can be recorded by the same Serial and Serial port is for communication. In my projects I use Eclipse and I record my atmegas using an Arduino board. Then just take them out and add the PCB project.

See this and this

Hmm, I've actually looked at that, but it costs more and also needs a FTDI chip (as soon as you take the MCU off the arduino board.
When the ATmega 328 (in the nano arduino) has the bootloader, it's good to go, fully serial? ;D
And even then the nano arduino has an ICSP header which I could use?
But anyway, this question seems solved! It is possible, but the details may vary for each user.


text:
Making CS (chip select) work in SPI (for and SD card and OLED)

I'm working on a project that will log data to an SD card and display a user interface on an OLED. The SparkFun OLED breakout was super easy to set up. I was also able to get the SD-Card library working independently, though that was harder.
The trouble is when I combine these examples the SD card only writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine.  I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.
My pins are connected as follows:
          SD CARD      OLED
MOSI        A5            A5     same pin
MISO        A4            --     just SD connected
SCK         A3            A3     same pin
CS          A1            A2     different pins

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way.  What could I try next?
Here is the code:

 #include "application.h"
 #include "sd-card-library/sd-card-library.h"
 #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
 #include "math.h"

 //////////////////////////////////
 // MicroOLED Object Declaration //
 //////////////////////////////////
 // Declare a MicroOLED object. If no parameters are supplied,
 // default pins are used, which will work for the Photon Micro
 // OLED Shield (RST=D7, DC=D6, CS=A2)
 // Since I use A1 as the chip select pin for the SD card these
 // defaults seem fine.

    MicroOLED oled;

 // Declare a file object?

    File myFile;

 // These are the pins for the SD card. A5, A4, and A3 are all
 // shared by the OLED.

    const uint8_t chipSelectSD = A1;
    const uint8_t mosiPin = A5;
    const uint8_t misoPin = A4;
    const uint8_t clockPin = A3;

 ////////////
 // setup //
 ////////////
 void setup() {
  delay(500);

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("this text was printed to the SD card during setup");
  dataFile.close();

  oled.begin();  // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  delay(1000);  // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

               }//end setup

//////////////////
// main loop //
//////////////////
void loop()  {

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("The text was added during the loop.");
  dataFile.close();

//test the display with text and pixels.
  printTitle("Pixels", 1);
  for (int i=0; i<512; i++)
  { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
  oled.display(); }
   delay(9000);

               } //end loop

//-------------------------//
// function to print titles //
//-------------------------//
  void printTitle(String title, int font) {
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
  middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
                                           } //end title function

This is how the SD card is hooked up.
  oled.begin();  // Initialize the OLED

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.
I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

Try interfacing with the OLED using I2C. That might avoid the contention with the SD card.

Try explicitly setting the CS pin used by MicroOLED oled(rst, dc, cs)

I2C is notoriously buggy on this micro. I'll see if anyone has it working.
I added  "MicroOLED oled(MODE_SPI,D7, D6, A2);"  it still has the same error.

There are devices that "break" the bus by not being able to work on systems that have more than one SPI slave. In that case you can do nothing to fix it but use devices that don't have this behaviour.

I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.
Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???


text:
How can I reduce speed of motor with motor shield?
I'm using Arduino and Adafruit to control 4 motors for a little robot.
I have this code example:

#include <AFMotor.h>

AF_DCMotor motor1(1, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor2(2, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor3(3, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor4(4, MOTOR12_1KHZ); // create motor #2, 64KHz pwm

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  motor1.setSpeed(200);     // set the speed to 200/255
  motor2.setSpeed(200);     // set the speed to 200/255
  motor3.setSpeed(200);     // set the speed to 200/255
  motor4.setSpeed(200);     // set the speed to 200/255
}

void loop() {
  Serial.print("tick");

  motor1.run(FORWARD);      // turn it on going forward
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(1000);

  Serial.print("tock");
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(1000);

  Serial.print("tack");
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
  delay(1000);

}

I want to reduce speed, because now is very fast. If I change setSpeed, the motor have no more force and don't run or not good. Do you know what I'm doing wrong?
Thanks
Best regards

if reducing speed from setSpeed does not works for you, Its probably power supply/motorDC problem. Keep in minds that motor DC is not a linear actuator