Will adding Ethernet shield reduce the IO count of Arduino? I have searched this question but could not find an answer on this site.

There was a related question - Latest Ethernet shield - used pins, how to bypass restrictions on arduino forums, but, I was unable to understand what the answer meant.

The background of my project:

My project requires

| S.No. | IO Type | IO Qty |
|-------+---------+--------|
| 1     | AI      |     11 |
| 2     | DI      |      9 |
| 3     | DO      |     11 |

I intend to connect this arduino board via ethernet shield to a network. I want to receive data over the network for display and storage purposes on a PC.

Questions:

What Arduino board should I select?
Will ESP8266 be compatiable with the suggested model?
Are there any pitfalls that should be considered when making the
selection for this design.

P.S: I have raised the same question on the arduino forum. If I get an answer- I will share my answer here as well

You should use a Mega if you really need so many gpio pins.

Arduino Ethernet and WiFi shields and their clones use 3 GPIO pins with SPI function with connection on ICSP header. Next they use the Slave Select signaling pin 10 and the SD card Slave Select signaling pin 4. The shields are compatible with Mega. So you should still have enough pins.

esp8266 can be connected to SPI. then it uses the same pins like the Ethernet shield except of the SD card slave select pin.

if you connect esp8266 to Serial port, then all the pins are free. Mega has 4 Serials.

esp8266 is cheaper but you need to connect it with level shifters and have a good power supply. there is no good esp8266 shield for now. The Mega + WiFi board from Robotdyn has the esp8266 on board with Serial connection.


Arduino retrieving PHP echo using ESP8266 I want to retrieve the echo string. Here is my php code

<?php
    echo "<hello word!>";
?>

I am using ESP8266 and Arduino Uno. I have managed to send the request but it's not returning the string from my php file. Any idea where i went wrong with my code? Thanks in advance

#include <SoftwareSerial.h>
#include <Ethernet.h>
#include <SPI.h>

SoftwareSerial esp(2, 3);// RX, TX

String ssid ="";
String password="";

String server = "http://domain.com/";
String location = "/retrieveInfo.php";

char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?

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

void loop()
{
  String pageValue = connectAndRead(); //connect to the server and read the output
  Serial.println(pageValue); //print out the findings.
  delay(5000); //wait 5 seconds before connecting again
}

String connectAndRead()
{
  //connect to the server
  Serial.println("Connecting...");
    String cmd2 = "AT+CIPSTART=2\"TCP\",\"" + server + "\",80";
    esp.println(cmd2);
    delay(4000);

    if (esp.find("OK"))
      {
        Serial.println("TCP Connection Ready.");
      }
             String postRequest = "GET" + location + "HTTP/1.0\r\n";
             String cmd4 = "AT+CIPSEND=2,80";
             delay(4000);
             esp.println(cmd4);
             esp.println(postRequest.length());
             delay(4000);

             if (esp.find(">"))
                {
                   Serial.println("Sending...");
                   delay(1200);
                   esp.println(postRequest);
                   esp.println();

                  if (esp.find("SEND OK"))
                  {
                    Serial.println("Packet sent");
                    Serial.println();
                    delay(4000);
                    //Connected - Read the page
                    return readPage(); //go and read the output

                 }
                  else
                  {
                    Serial.println("Connection failed");
                  }
            }
    else
      {
        Serial.println("TCP Connection Not Ready.");
      }
}

String readPage()
{
  //read the page, and capture & return everything between '<' and '>'

  stringPos = 0;
  memset( &inString, 0, 32 ); //clear inString memory

  while(true)
  {
      if (esp.available())
        {
          char c = esp.read();
          if (c == '<' ) { //'<' is our begining character
            startRead = true; //Ready to start reading the part
          }else if(startRead){

            if(c != '>'){ //'>' is our ending character
              inString[stringPos] = c;
              stringPos ++;
        }
        else
          {
            //got what we need here! We can disconnect now
            startRead = false;
            return inString;

         }

      }
    }

  }
}

void connectWifi()
  {

    String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"\r\n";
    esp.println(cmd);
    delay(5000);

    if(esp.find("OK"))
      {
        Serial.println("Connected!");
        delay(4000);
        enableconn();
        delay(1000);
      }

    else
      {
        Serial.println("Cannot connect to wifi");
        connectWifi();
      }

  }

void enableconn()
  {
    String cmd1 = "AT+CIPMUX=1";
    esp.println(cmd1);
    delay(4000);
    if (esp.find("OK"))
      {
      Serial.println("Ok");
      delay(4000);
      connectAndRead();
      }
     else
      {
        Serial.println("Cannot enable multiple connections");
      }
  }

for some reason, the line "return readPage();" isn't returning any value. Any heads up would be much appreciated. This is my output in the serial monitor

It looks like you post request may be missing a CRLF at the end (it needs two) and some spaces.

I think you need this:

 String postRequest = "GET " + location + "\r\nHTTP 1.0\r\n\r\n";

My suggestion would be to get a REST client (like the one you can get for Chrome as an App) and send the message to your server through that and see what the difference is.


Servo Speed Changer with Buttons ok so yesterday i was in trouble with the buttons, with help from you i got over it and everything worked fine with the 1st speed of the servo, then i added the other 2 speeds and it looks like it all messed up... the buttons don`t respond as they should and the servo moves very weirdly.
Here is the code:

const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
#include <Servo.h>
Servo servo1;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  servo1.attach(9);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int position;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

      if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
            x++;
            Serial.println("on1");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x--;
            Serial.println("on2");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
       }
          delay(1000);

lastButton1State = button1State;
lastButton2State = button2State;

  if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position < 360; position += 2)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position <360; position += 5)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
        for(position = 0; position < 360; position += 10)
          {
            servo1.write(position);
            delay(20);
          }
    }
}

There may be better ways to mitigate button bounce. Check this link for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.

Determine if the servos you are using are capable of the range you are demanding.  Some servos only travel from 0 degrees to 180 degrees.  Your code is asking the servo to travel from 0 degrees to 360 degrees.  Also, it is unlikely that any normal servo can travel this far.  Most servos use a potentiometer as a feed back sensor.  And most potentiometers can only be turned to something less than 1 full revolution.

It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops.  Understand that normal servos can not make complete revolutions.  They need to stay within their designed limit of rotation.  If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.

Consider your last loop.  You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps.  You are allowing 20ms per step.  That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second.  Some but not all servos can move that fast.


Pass variable in a URL I am working on code where I am able to manually enter the value in the URL to let the PHP code save it in the database, but I'm unsure how to do it with a variable in a loop running. This is the URL:

student.cs.hioa.no/~s180343/updatedb.php?verdi=25

Code:

void setup() {
  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);
  Serial.println("Ready");

  // run various example processes

}

void loop() {
   runCurl();
   delay(10000);
}

void runCurl() {
  // Launch "curl" command and get Arduino ascii art logo from the network
  // curl is command line program for transferring data using different internet protocols
  Process p;        // Create a process and call it "p"
  p.begin("curl");  // Process that launch the "curl" command
  p.addParameter("student.cs.hioa.no/~s180343/updatedb.php?verdi=25"); // Add the URL parameter to "curl"
  p.run();      // Run the process and wait for its termination

  // A process output can be read with the stream methods
  while (p.available()>0) {
    char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
}

You can pass in a variable into a function. Something like this:

void runCurl(int verdi) {
    ...
    String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
    myUrl += verdi;
    p.addParameter(myUrl);
    ...
}

You call the function like this, now:

runCurl(1);
runCurl(2);
runCurl(someVar);

and so on. Since it's already in your main loop() function, you just need to set pass in a different number based on whatever it is you're trying to do.


What happens if I power the Arduino with both the USB and external power voltage simultaneously? I am a new Arduino user. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Basically, I want to automatically shut down the computer after saving all open documents before my UPS battery goes out whenever I am not there to manually shut it down. I am trying to notify the computer about the power failures of main supply - AC 220V 50 Hz (notification/signal sent when power goes out) via USB using Arduino. I am thinking that this can be done by using the external voltage power supply pin. Whenever power goes out in the mains, the external voltage power supply pin will drop to 0 V from 7 V. The value of the voltage can be read using software ( I am unclear about this: Can it be done? If yes, how?). The Arduino will still be powered up as it is connected to USB of computer and thereby communicates to the computer about the power failure.

I am a novice user of Arduino. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Lets study the schematic of Arduino UNO R3

The input from the power supply plug (PWRIN, the power jack) goes through a diode D1 (to prevent reverse polarity), and feeds a NCP1117 regulator that down converts it to the 5v supply that feeds the 5v parts.

The alternative supply comes from the USB plug (USBVCC). The relevant circuit is shown below

The USB power lines goes through a P-mosfet (T1) that operates as a switch and then goes to the +5V node (that is the +5v regulator output as shown in the first schematic).

The mosfet is controlled by an LMV358 operational amplifier (OPAMP) that operates as a comparator.
The negative input of the opamp is tied to 3.3V and the positive one fed through a voltage divider with half the Vin supply level.

When Vin >6.6V then the + input of the opamp become higher than the - input and the opamp turns the mosfet off.
When Vin <6.6V then the + input of the opamp become lower than the - input and the opamp turns the mosfet on.

Note that Vin is after the input diode so it's about 0.6V lower than the external connected power supply level. So when there is power supply connected to the power input that is higher than 6.6V+0.6V (where 0.6V is the diode D1 voltage drop), then the USB supply line is cutoff (because the mosfet turns off) and the power is provided from the power plug. Connecting or disconnecting the USB supply in this case will not make a difference, so you can have both power supplies connected simultaneously, only when the power input drops below the specified level (about 6.6V+0.6V=7.2V), the USB will start powering the board.


Connect multiple RFID-RC522 cards? I have a project that requires 4 different RFID-RC522 readers.  The RFID-RC522 has the following pins:

SDA
SCK
MOSI
MISO
IRQ
GND
RST
3.3V

I have read that the SDA pin is used for selecting the active device, So I'm thinking that these devices can share data pins.  Is it possible to connect multiple RFID-RC522 readers to the same 3.3V, RST, GND, IRQ, MISO, MOSI and SCK pins if you use a different pin for each SDA?  If so, this would save me a lot of pins.  So far, I have only seen direction on how to connect one RFID-RC522 to an Arduino.

I'm using the MFRC522 library.  It appears to only support one reader because it only allows one SS pin to be identified in the constructor, and offers no way to change it later.  An I missing something or do I need another library?

Connect everyone to the MOSI / MISO / SCK and ground, then define every SDA all the way around. and set respectively high low depending on where you want to write.

How ever im not sure if you need to set high or low if you want to read. But since you got multiple you can play around with that your self. Feel free to add to this question with the result for future googlers.

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN           7          // Configurable, see typical pin layout above
#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

....

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

....

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card


Help adding 3 more on/off switches so that I can control 4 LEDs This code is working fine to switch on/off one LED. Can anyone help me add 3 more on/off buttons so that I can control 4 LEDs?

#include <String.h>
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED
};
byte ip[] = {
  192 , 168 , 2 , 20
};
byte gateway[] = {
  192 , 168 , 2 , 1
};
byte subnet[] = {
  255 , 255 , 255, 0
};
EthernetServer server(80);
String richiesta;
int pinLed = 9;

void setup() {
  Ethernet.begin(mac,ip,gateway,subnet);
  pinMode(pinLed,OUTPUT);
  Serial.begin(9600);
  richiesta = "";
}

void loop() {
  EthernetClient client = server.available();
  if(client) {
    Serial.println("Tujse na ho payega");
    while(client.connected()) {
      if(client.available()) {
        char c = client.read();
        richiesta.concat(c);
        if(c == '\n') {
          Serial.print(richiesta);
          if(richiesta.indexOf("Led=1")>0) {
            Serial.println("Pin will be high");
            digitalWrite(pinLed,HIGH);
          } else {
            Serial.println("Pin will be low");
            digitalWrite(pinLed,LOW);
          }
          client.println("HTTP/1.1 200 ok");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<title> Home Automation</title>");
          client.print(" ButtonOn  Buttonoff ");
          client.stop();
          richiesta = "";
        }
      }
    }
  }
}

Use arrays, one for switches, one for leds. I don't see the code for leds in your code.

Note that you need 8 pins (4 for switches, 4 for leds).

Initialize them, e.g.

int switchPins[] = { 2, 3, 4, 5 };

Same for leds

int ledPins[] = {6, 7, 8, 9};

To access them, use a for loop:

for (int iLed = 0; iLed < 4; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

Because 4 might be used a lot, consider them making const or define:

#define NR_OF_LEDS 4

for (int iLed = 0; iLed < NR_OF_LEDS; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

or use the length of the array

for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}


avrdude: stk500_recv(): programmer is not responding: lilypad arduino i realise this is probably the most common error that is asked about on this forum, but it is a major issue for me. i have an arduino lilypad main board (with the ATMega328P, boot loader already burned), and a generic FTDI serial to usb adapter plugged into my windows 10 laptop. When i try to upload the Blink program from the Arduino IDE, it fails with the error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfe

i am using a windows 10 laptop, the Arduino IDE from the windows store. this is a new lilypad, and i have never been able to upload to it. take note that when i reset the board, the pin13 light does flash (but  not the way the Blink program specifies, obviously.

i have already tried:

Rebooting my computer
Restarting the IDE
Turning the COM port on and off
Taking out the RX/TX wires from the FTDI converter
Pressing the reset button right before uploading (or during uploading)
Changing which board it is set as in the IDE
Unplugging and re-plugging the USB-Serial converter

if you have any other possible solutions they would be appreciated, thanks

Last time I bought one of the Lilypads, it did not have a bootloader. I had to buy a SMD programmer adapter that presses down over the 328P chip to bootload it as the board did not break out the ICSP pins to any pads.

I think I got mine here https://hobbyking.com/en_us/atmel-atmega-socket-firmware-flashing-tool.html but I haven't seen them in stock for a while.  Very handy tool tho. Another option is to tack wires to the appropriate uC pins and, connected to a 2x3 header that your Programmer can connect to. Remove the wires when done.


434 RF Transmitter and Receiver for distance measurement problem As a student I'm working on a project where we use 434 MHz RF Transmitter and receiver pairs for distance measurement. I know that this technology is not a good choice for this, but we have to deal with this problem due to external constraints.

Here is the receiver: RF Link Receiver - 4800bps (434MHz).

I did a little bit of research how these receivers works, but I found it a bit overwhelming to understand them bit by bit.

We want to use the signal strength for distance measurement. So we tried sending pulses of signals from one transmitter to a receiver. If the amplitude of the signal received is higher than a certain value (let's say 3V), it sends back a signal (let's call it trigger signal) in the gap between the two pulses.

The problem is that that these signals seems to affect each other even though they are not in the same time (so it's not superposition that we are talking about). When there is a signal sent back, the next pulse will be lower, which results in false distance measurement.

The whole difficulty is (to me it seems) that we are not using these signals to send data, we are using it for distance measurement. My idea is that we are using too long pulses and the AC coupling in the receiver doesn't tolerate it, but again, I don't have enough electrical knowledge to safely say that.

I know this is not descriptive, but I don't know how to make it more descriptive, so I'm happy to answer more questions on demand.

It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.

This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.

A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

compare on a two channel scope the signal pulse driving the transmitter
and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.

I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.


MySQL Connector/Arduino insert data from row into an array I'm new here.
These days I have been working with the MySQL Connector/ Arduino library. So, my problem is how can i retrieve a rows data so as to enable an output. I have written some code, which was going pretty good, but here is where my problem is introduced:

void query_analysis_states () {
  row_values *row = NULL;
  column_names *columns = NULL;
  SQL_SETUP.cmd_query(QUERY_STATE_SQL);
  columns = SQL_SETUP.get_columns();
  do {
    row = SQL_SETUP.get_next_row();
    if (row != NULL) {
      for (int f = 0; f < columns->num_fields; f++) {
        state_Array[f] = atoi(row->values[f]);
      }
    }
  } while (row != NULL);
}

So the problem is that if I put a serial.print inside the for loop, I get the correct states which I have requested. If, I put it outside, I get them all wrong, like they are gone missing, for example I get states 1, 0, 1 and then 0, 0, 0 or something else. That means that the array also which plays the role of capturing the data from the row doesn't work when I call the method. Can anyone please help me? If you want me to post the rest of the code, please tell me. Thank you in advance.

Sorry for the inconvenience, problem solved!
The problem was simple as I was getting both two columns except one!

void query_analysis_gates() {
  row_values *row = NULL;
  column_names *columns = NULL;
  SQL_SETUP.cmd_query(QUERY_GATE_SQL);
  columns = SQL_SETUP.get_columns();
  counter = 0;
  do {
    row = SQL_SETUP.get_next_row();
    if (row != NULL) {
      gate_Array[counter] = atoi(row->values[0]);
      counter++;
    }
  } while (row != NULL);
}

I provide this if anyone needs help with another method but it does the same function.


Sending data over TCP connection in one piece I'm trying to send short strings via Java client to Arduino server and vice versa. Sending data to client goes fine, but when I try to send data to arduino it cuts the string into bytes and then sends the first letter.  Will the following work?

for(int i = 0; i < data.length(); i++)

Even if it can be sent as characters I want to send it in one piece, because strings are very short so there should be no problems with length.

EDIT: Alright, I read client.read() documentation, so the problem is at arduino.

This is my java code:

public class TCP {
static Socket clientSocket;

public static void main(String args[]) throws Exception {
    clientSocket = new Socket("10.10.10.57", 5000);
    sendToServer("HAI THERE\n");
    String msg = getFromServer();
    System.out.println(msg);
    close();
}

static void sendToServer(String msg) throws Exception {
    //create output stream attached to socket
    PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    //send msg to server
    outToServer.print(msg + '\n');
    outToServer.flush();
}

static String getFromServer() throws Exception{
    //create input stream attached to socket
    InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
    BufferedReader inFromServer = new BufferedReader(isr);
    //read line from server
    String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
    return res;
}

static void close() throws IOException{
    clientSocket.close();
}
}

This code sends only one byte at the same time.It might be problem in my arduino code, since I read it with

char c = client.read()

One more thing. If there is any java master, I would like to know what to do with exceptions. How should I handle disconnected socket, failed connection to server, and so forth?

The problem is, that "char" is just one character. So you have to build your return out of the chars... if you want to use the "client.read()" function.

String res = ""; //this will be the resived msg after the loop
do {
   char c = client.read(); //c will be -1 if no byte is left
   if(c!=-1)
       strcat(res, String(c)); //Append the char to the result string
} while(c!=-1);

//Code is not tested!!!

To your java problem... just put your code parts into try catchs not whole functions (remove it for the function and add it on the points eclipse tell you to). So you can react to each error individually. Then put client stuff in a own thread so it not blocks any other stuff. Every disconnect or faild connection will throw an exception if you dont catch it with an if. So you have to handel it their (try to reconnect or something)

EDIT:

static void close() {
    try {
        client.close();
    } catch (IOException e) {
        system.out.println(e.toString()); //Print the error or do something else

    }
}


Wemos Mini & Pro Micro Serial connection While using a 3.3v Pro Mini & Wemos mini to communicate via Serial was successful, when tried with a 5v Pro Micro it fails.
To overcome different logic level I used a 10K + 20K resistors to lower Pro-Micro's 5v to 3.3v successfully to Tx and Rx pins. Also since they are on the same PCB, GND pins are connected and RAW to 5V at wemos mini  is also connected. At the moment, it is powered up using MCU's USB input ( tried to connect to Pro-Micro only, Wemos Only, and both ).

What might be the problem ?

You don't need a logic level conversion between 5 V Micro Arduino and 3.3 V Wemos D1 mini. The 5 V ATmega 328p reads 3.3 V as HIGH and the esp8266 can tolerate 5 V logic level for tests. For long term connection you can add logic level conversion with a voltage divider to convert the 5 V of ATmega TX to 3.3 V of esp8266 RX.
RX/TX pins on Arduino Mini are Serial.
RX/TX pins on Arduino Micro are Serial1.
Serial is only USB on Micro.


Can I do speech to text converting with arduino? I am a beginner to arduino. I want to make such a robot that can convert my speech into text and save the texts in a .txt file in the SD card attached to my arduino.
Can I do so? If it is possible please someone give me the instruction. Someone help me please...

There are many Arduino type boards.  Some, like the galileo from Intel, are very powerful.  And are more expensive than the basic Arduino Uno.  It may be possible to program such a board for speech to text conversion.  But it is arguable that using a modern laptop with built in features (microphone, keyboard, display, speaker, ect) would make the task easier.

Also, consider current industry standards.  Many text to speech applications are now centered around cloud computing.  Think of Siri, Alexa and Cortana.  But even if you do, consider that the Arduino Uno only contains enough RAM to record an "utterance" of speech. On the order of a second, maybe two.

Finally, consider COTS (Common Off The Shelf) parts (Arduino shields).  Searching "arduino speech to text" I found at least one device.


Node.js cannot recognize characters from the serial port The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters.  The if statement does not work with characters.  I have tried both == and === in the if statement

var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline
var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
  baudRate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
if(data === 'c'){/// c is not recognized
  console.log('data received: ' + data)
}

})
serialPort.on('open', function () {
  console.log('Communication is on!')
})

The Arduino code is as follows:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX
int x = 0;
int y = -30000;
int z = 0;
String data;
char command = 'q';
int left = 0;
int right = 0;
int left_pwm = 0;
int right_pwm = 0;

void setup() {
  mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  Serial.begin(9600);
  }
void loop() {//map and compass data
if (y==30000) {
 mySerial.println('c');
 delay(5);
 mySerial.println(299);
 delay(5);
 z = -25000;
 }

 if(z==30000){
 mySerial.println('lon');
 delay(5);
  mySerial.println(529);
  delay(5);
  mySerial.println('lat');
 delay(5);
   mySerial.println(522);
          y = -30000;
    }
  y++; z++;

  if (!mySerial.available()) {
    return;
  }

  data = mySerial.readString();
   sscanf(data.c_str(), "%c%01d%01d%03d,%03d", &command, &left, &right, &left_pwm, &right_pwm);

  if (command == 'n') { // we got a navigation command
    // update the GPIO accordingly, this only happens once after a new 'n' command has been received
    Serial.print(command);
    Serial.print(left);
    Serial.print(right);
    Serial.print(left_pwm);
    Serial.print(",");
    Serial.println(right_pwm);
    }

    }////end loop

If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the 'ņ' character is removed from the string. But Serial.println() sends "\r\n" as line ending. That means, that your string is "c\r", which is not equal to "c".

By using the trim() method of the String type, you can remove all white space from start and end of the string, including line ending characters like '\r'.


'MeDCMotor' does not name a type error inside mBlock I was using a 3rd party programming enviroment, mBlock 3.4.5 for making C++ Arduino programmes with a graphical programming language. I was compiling a program and the following eroor came up.

project_Untitled0_0.ino:65:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino:66:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino: In function 'void move(int, int)':
project_Untitled0_0.ino:85:7: error: 'motor_9' was not declared in this scope
project_Untitled0_0.ino:85:24: error: 'M1' was not declared in this scope
project_Untitled0_0.ino:86:7: error: 'motor_10' was not declared in this scope
'MeDCMotor' does not name a type

I took another look at the program and there were some lines of code that seem they are added in the program by deafult:

MeDCMotor motor_9(9);
MeDCMotor motor_10(10);
void move(int direction, int speed)
{
      int leftSpeed = 0;
      int rightSpeed = 0;
      if(direction == 1){
            leftSpeed = speed;
            rightSpeed = speed;
      }else if(direction == 2){
            leftSpeed = -speed;
            rightSpeed = -speed;
      }else if(direction == 3){
            leftSpeed = -speed;
            rightSpeed = speed;
      }else if(direction == 4){
            leftSpeed = speed;
            rightSpeed = -speed;
      }
      motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
      motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
}

Since the program does not recognise the MeDCMotor class the program failed to upload.

I am running Windows 10 home edition on a 64-bit laptop.

Is there a way to remove the lines of code that prevent me from uploading the sketch or are there other ways to solve it?

I looked at some entries in a google search for error: 'MeDCMotor' does not name a type, such as 1, 2, 3 and 4.  The first three of those latter four links directly address the question you ask, and none of them answer it clearly, except to suggest re-downloading or re-installing the makeblock library.  While the fourth link addresses a “does not name a type” error for another library, rather than for makeblock, it has a relatively clear explanation of the problem for that other library:

  So, as supplied, the ArduinoByteBuffer.zip file had a complex set of sub-directories, and the two files ByteBuffer.ccp and ByteBuffer.h were located one level down in: \ArduinoByteBuffers\ByteBuffer\

  When I 'installed' the library, it went into the directory:

    C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.h

  To solve the problem I moved them up a level to:

    C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.h

  That seemed to be the key - moving the two files (*.ccp and *.h) out of the subdirectory.

Instead of following ordinary C or C++ library-finding rules, the Arduino IDE copies sets of files into a temporary directory according to its own rules when compiling a sketch.  You'll need to move your makeblock library files around to match up with Arduino IDE conventions.


Arduino ATmega 2560 frequency measurement I would like to measure frequency with an Arduino 2560 board. The approach is to use a timer interrupt set to one second and pin interrupt to count interrupts in one second.

The problem I have is that I get the wrong frequency. On my frequency generator I set up a frequency of 1000 Hz in my program I get 1006 Hz instead of 1000 Hz.

What am I doing wrong?

Here is my program. In the stup method I have declared a timer. When the signal comes on pin 2, the counter is increased by 1. After one second passed the flag bData is raised. If the flag is true then I print out a frequency on serial port.

#include <SPI.h>
#include <Ethernet.h>
#include <Math.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);
const byte interruptPinTemp = 2;
const byte interruptPinSlanost = 3;
//konstante za SBE-3
const double g = 4.85442486e-003;
const double h = 6.77300393e-004;
const double i = 2.65502731e-005;
const double j = 2.06782794e-006;
const double f = 1000.0;
volatile int cnt = 0;
volatile int cnt1 = 0;
volatile double slanost = 0;
volatile double slanost1 = 0;
int timer1_counter;
boolean bData = false;
volatile int dvesek = 1;

void beriTemperatura() {
  cnt++;
}

void beriSlanost() {
  slanost++;
}

double calcTemp(double frekvenca) {
  double logRes = log(f / frekvenca);
  return 1.0 / (g + (h * logRes) + (i * pow(logRes, 2.0)) + (j * pow(logRes, 3.0))) - 273.15;
}

void setup() {
  Serial.begin(9600);       // inicializacija serijskega porta
  noInterrupts();           // disable all interrupts
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  pinMode(interruptPinTemp, INPUT_PULLUP);
  pinMode(interruptPinSlanost, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPinTemp), beriTemperatura, CHANGE);
  attachInterrupt(digitalPinToInterrupt(interruptPinSlanost), beriSlanost, CHANGE);
  TCCR1A = 0;
  TCCR1B = 0;
  timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();
}

//Timer interrupt na 1 sekundo
ISR(TIMER1_OVF_vect) {
  // interrupt service routine
  TCNT1 = timer1_counter;   // preload timer
  cnt1 = cnt ;               // prepisemo vrednost v cnt1
  bData = true;             // postavimo flag
  cnt = 0;  // resetiramo counter
}

void loop() {
  // če je postavljen flag, da so podatki jih izpišemo ali naredimo karkoli drugega
  if (bData == true) {
    bData = false;
    Serial.println(calcTemp(cnt1), 3);
    Serial.println(cnt1);
  }
}

Here is the frequency from my generator:

And here is a frequency measured with my board:

What is wrong that I get 1006 Hz instead of 1000 Hz?

If I raise the frequency for example to 5 kHz then I get 5032 Hz in my program (32 Hz to0 much).

Thank you for any advice.

TCNT1 = timer1_counter;   // preload timer

When you load the offset (timer1_counter), there are some values in the timer1 prescaler (and potentially TCNT1 if the prescaler isn't sufficient large, or the input pulse train is fast). By assigning a value to TCNT1, you would have written over the values in the prescaler / TCNT1 -> read the datasheet on that.

The solution?

Optimal: use a timer with auto-reload function. a timer with output compare can be adopted here as well.
Increment the counter: TCNT1 += timer1_counter; // preload timer, if timer has a 1:1 prescaler.

Or to use the timer to count the pulse and another to provide the time base.


Need help: Cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive] I'm trying to convert the string that I receive from the Websocket to uint8_t that I can copy to the data bytes of CAN protocol frame. I'm using an ESP32 chip and programming it on an Arduino IDE. The string that it receives from the websocket is "0322F12155555555".
#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <esp32_can.h>
#include <SPI.h>
#include <string.h>

uint8_t payload1;
char payload2[100];
...
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
...
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num,
                      WStype_t type,
                      uint8_t * payload,
                      size_t length) {
...
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      strcpy(payload2, (const char*)payload);
      payload1 = (uint8_t)(payload2);
...

Error:
error: cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]
       payload1 = (uint8_t)(payload2);
                                    ^

I'm segmenting the data into an array later, but I'm not confident that my cast is correct. Can someone please help with this? Thanks
-- Keith

You can't just cast a string to a numeric type - C just doesn't work that way. What you're actually casting is the address in memory that the string resides at.
Instead you need to take the content of the string and interpret it.
For instance, you might take each pair of characters and combine them into a HEX value in a string that you then interpret as a number. That could be done a number of ways.
For example:
char temp[3]; // Temporary space for the conversion string
// Copy two characters into the temporary string
temp[0] = payload[0];
temp[1] = payload[1];
// and terminate the string properly
temp[2] = 0;
// Convert the string using base 16
uint8_t val = strtol(temp, NULL, 16);

In your example string you have 16 characters, which would be 8 bytes of data. So you could put it in a loop:
char temp[3]; // Temporary space for the conversion string
uint8_t vals[8]; // Array to store your values

// Iterate over the values
for (int i = 0; i < 8; i++) {
    // Copy two characters into the temporary string
    temp[0] = payload[i * 2];
    temp[1] = payload[i * 2 + 1];
    // and terminate the string properly
    temp[2] = 0;
    // Convert the string using base 16
    vals[i] = strtol(temp, NULL, 16);
}

Of course there are "lighter" ways of doing it that don't involve an intermediate string or the strtol() function.  For example I often use this little function:
uint8_t h2d(char hex) {
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

That takes a single character and converts it from hex to decimal. So you can combine that with bit shifting and OR to create a byte from two characters:
val = h2d(payload[0]) << 4 | h2d(payload[1]);

In your loop that would look like:
for (int i = 0; i < 8; i++) {
    // Convert the string using base 16
    vals[i] = h2d(payload[i * 2]) << 4 | h2d(payload[i * 2 + 1]);
}


Print when echo is read by HR-S04 sensor I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.

The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?

int trig1 = 3; //Trig 1
int echo1 = 4; //echo1
int ECHO1;
double pingTime1;

void setup()
{
  Serial.begin(9600);
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

  while (ECHO1 == 0) //continuous loop until echo is HIGH
  {
    digitalWrite(trig1,LOW);
    delay(100);
    digitalWrite(trig1,HIGH);
    Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
   ECHO1 = digitalRead(echo1);
  }
  pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
  pingTime1 = pingTime1*1000; //convert microseconds to seconds

}

A couple things:

1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()

2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.

3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.

4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.

I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.

Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.

// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');


Get data from website with ESP8266 using AT commands I'm trying to get data from a website by sending a HTTP GET request via AT commands for the ESP8266. Here is my current code:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

Running this code I get the following response:

AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,

It looks like it gets a response, but nothing is printed.

I tried doing the same thing by sending the AT commands manually using this code:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial ESP8266 (rxPin, txPin);

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

void loop() {
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

With this approach I actually get a response:

AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,275:HTTP/1.1 200 OK
Date: Thu, 22 Dec 2016 20:20:47 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
Last-Modified: Thu, 22 Dec 2016 19:37:22 GMT
ETag: "13-5444465f69339"
Accept-Ranges: bytes
Content-Length: 19
Connection: close
Content-Type: text/html

THIS IS MY WEBSITE!4,CLOSED

Does anyone know what is happening and how I can get this to work with my Arduino code?

Other ways to get data from a website are also welcome.

As pointed out in the first comment, my printResponse() function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /test.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}


How do I send an arduino PIN state to a local PC using the ethernet connection? As a PIN goes high I need to trigger an event that will send the IP or MAC of the arduino and the PIN state over the wired Ethernet to a local computer. I am using an Ethernet shield to send and receive from the arduino but I am stumped on how to send and process the information at the PC. I will have 42 Arduinos on the network all set to send PIN information over the wired Ethernet. Sounds simple but after a days research I am now looking at other solutions.  I currently have the faithful Uno with the network shield as my prototype. For the final install I can purchase any of the arduino range like the Yun,Duo etc. if this would help. Any direction would be welcomed.

The simplest method is to set up a web server on your PC.  You haven't mentioned what OS you run (which is kind of critical), so looking into WAMP or LAMP ("Windows/Apache/MySQL/PHP", or "Linux/Apache/MySQL/PHP") is probably your best option.

Once you have a working web server you can pretty much use verbatim the Ethernet examples for connecting to a remote website ("Web Client").  That website would be your local PC address, and you send whatever parameters you want.

You then write a small PHP script (or whatever language you program your chosen web server in) to accept that web request and process it accordingly.

In general you never need to explicitly send the IP address since it is encapsulated as part of the actual socket connection information and is generally made available through various means to your web page (see $_SERVER in PHP for example).

If you want to get more "low level" and lighter weight then you would most likely be looking at writing a UDP server on your computer which receives UDP requests from the Arduinos and processes them as needed.  The content of a UDP request is entirely up to you, but programming a server for dealing with it is beyond the scope of an answer here - suffice it to say there are plenty of resources online available for all the major operating systems and programming languages on how to write UDP servers.


Undervoltage from solar panels So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.

The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage  from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.

You have selected a number of things that don't go well together. It is possible to use relays or mosfets to switch between batteries, and the Arduino could be used to measure a voltage. Or you can make a circuit with a few electronic components (e.g. a comparator). However, no one does it like that. It would be unreliable.

Every solar power charging module can handle darkness as well. Some modules will also create 5V.

This Adafruit module has no 5V output, it only contains the charging part: Adafruit:USB / DC / Solar Lithium Ion/Polymer charger - v2
It is out of stock at the moment, and you need solar cells, battery, a cable, and a DC-DC converter to make 5V.
When it is dark and the battery is empty, I assume the output drops and the Arduino stops working. Adafruit made a tutorial for it that shows the DC-DC converter and also Collin shows a DC-DC converter: Youtube, Collin's Lab: Solar

There are other modules like that. For example the Sparkfun Sunny Buddy.

Take care that the batteries don't get too hot.
It is possible to run some Arduino boards directly from a battery (3.1 to 4.2V). Then you would not need the DC-DC converter.
Buy solar cells that are the best in low light conditions. With enough sunlight, the power is no problem. It is the dark winter days that could be a problem.


How do I handle multiple interrupts and outputs simultaneously? I'd like to make a musical harp that utilizes break beam sensors.

I'd really appreciate guidance on these two questions:

How should I go about listening for multiple beam breaks at the same time? I'd like the box to be able to play cords, so I'd need to listen for the break beams while simultaneously taking the action do to other previous break beams. Are there any links to similar projects for guidance on handling multiple inputs (possibly multiple interrupts) at the same time, as well is multiple outputs?
Where is a good place to start to understand how to output non-buzzer sound with an Arduino? I bought a Adafruit Wave Shield to do the trick, but I'd appreciate advice on using this, or possibly taking an easier route.

My major concern is the first question however, and it makes me think I may need a Pi possibly? But I've never worked with those, so I'd like to avoid it if possible.

Thanks!  :)

I quite like rachet freaks's idea, however whilst making an example for you his answer hadn't been posted. SO i'll chip in anyway!

In general it is possible to control and measure more than one input and output at the same time by the use of millis(). millis() is an arduino function that returns the number of milliseconds since the arduino fired up.

This probably doesnt sound overly useful to you straight away. But millis can be used in place of delay() if used correctly. Essentially you create a long variable to hold the beginning of an event and check the time since that event started with an if statement. If the difference in the current time and the start time is equal to the time you want the event to occur. Stop the event.

I appreciate my explanation might not be overly clear. So I wrote an example sketch. The sketch has two button inputs. And two button outputs. If one of the buttons is pressed one led will blink for 10 seconds, pressing the button mid blink will extend the time the led blinks by another 10 seconds. Whilst this is happening if you press the second button the other led will turn on, but only when the button is pressed. Using delay() to achieve this would not work nearly as well.

//Setup led and button pins
int ledPin1 = 3;
int ledPin2 = 4;
int butPin1 = 5;
int butPin2 = 6;

//Setup timers
unsigned long currentMillis = 0;
unsigned long blinkStartMillis = 0;
unsigned long ledOnMillis1 = 0;
unsigned long ledOffMillis1 =0;

//Setup variables to store input and output states.
int ledState1 = 0, ledState2 = 0; //State 1 for on, 0 for off;
int butState1 = 0, butState2 = 0; //State 1 for trigger, 0 for off;

//Setup trigger for event
int blinkTrigger = 0;

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(butPin1, INPUT);
  pinMode(butPin2, INPUT);

  delay(500);
}

void loop() {
    //Sets current millis for this loop
    currentMillis = millis();

    //Reads Button States
    butState1 = digitalRead(butPin1);
    butState2 = digitalRead(butPin2);

    //Setup to start blink if button 1 input is high
    if(butState1) {
      blinkTrigger = 1;
      blinkStartMillis = currentMillis;
    }

    //Handles Blinking
    if(blinkTrigger) {

      //If led1 off, and has been off for 500 milliseconds. led 1 on
      if(ledState1 == 0 && currentMillis - LedOffMillis >= 500) {
        digitalWrite(ledPin1, HIGH);
        ledState1 = 1;
        ledOnMillis = currentMillis;
      }

      //If led1 on, and has been on for 500 milliseconds. led 1 off
      if(ledState1 == 1 && currentMillis - LedOnMillis >= 500) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        ledOffMillis = currentMillis;
      }

      //If led1 has been blinking for more than 10 seconds
      //Stop blinking
      if(currentMillis - blinkStartMillis > 10000) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        blinkTrigger = 0;
      }
    }

    //While Button 2 pressed led 2 on
    if(butState2) digitalWrite(ledPin2, HIGH);
    if(!butState2) digitalWrite(ledPin2, LOW);

}

Note: The code style is a bit off because i rushed it, I would also usually use structs to hold the timers and event triggers.

Now for the Wave module rachet is bang on the money, you would need a file for every single note and every single chord.

I hope I helped, if not for your project maybe you may have learnt how to handle more than one event using event timings.


Can't make Wee serial WiFi work with Arduino Uno I'm trying to plug a Wee serial WiFi module on my Arduino Uno, through an XBee shield .

I'm simply trying to make work the example from the library.

All I get is

setup begin
FW Version:
to station err
Join AP failure
setup end

The code i'm using :

#include <SoftwareSerial.h>
#include <doxygen.h>
#include <ESP8266.h>

SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */
ESP8266 wifi(mySerial);

#define SSID "yuflowoffice"
#define PASSWORD "cashless"

void setup(void) {
  Serial.begin(9600);
  mySerial.begin(115200);
  Serial.print("setup begin\r\n");

  Serial.print("FW Version: ");
  Serial.println(wifi.getVersion().c_str());

  if (wifi.setOprToStation()) {
    Serial.print("to station ok\r\n");
  } else {
    Serial.print("to station err\r\n");
  }
  delay(1500);

  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP: ");
    Serial.println(wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }

  Serial.print("setup end\r\n");
}

void loop(void) {
}

What can I do?

A look at https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h shows that when you pass a SoftwareSerial object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the begin() method of the SoftwareSerial object you passed (myserial) is called with 9600 baud. Thus, this line in your code:

    mySerial.begin(115200);

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of mySerial.begin() useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:

    ESP8266 wifi(mySerial, 115200);

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:

    //#define ESP8266_USE_SOFTWARE_SERIAL

and then save, since you are using SoftwareSerial to communicate with the module.


Mapping segments and memory allocation on a segment LCD driver I've just configured a segment LCD and driver, everything works fine, but because I decided to not use vias on the PCB, the connections between the two are mixed.

To be more precise, in order to display the number 12, both memory addresses should be accessed.

So right now it's impossible to display a single digit without mapping all the segments.

In static mode, this is how RAM memory is allocated to SEG0-SEG7 and SEG8-SEG15 respectively:

What I've tried was to create two multidimensional arrays and map possible combinations of the two digits, like this:

// 01 to 09
const byte map1[10][2] = {
  {B01110111, B111111 },
  {B01110001, B100111},
  {B01111011, B011111},
  {B01111011, B110111},
  {B01111101, B100111},
  {B01111110, B110111},
  {B01111110, B111111},
  {B01110011, B100111},
  {B01111111, B111111},
  {B01111111, B110111}
};

// 10 to 19
const byte map2[10][2] {
  {B00010111, B111100},
  {B00010001, B100100},
  {B00011011, B011100},
  {B00011011, B110100},
  {B00011101, B100100},
  {B00011110, B110100},
  {B00011110, B111100},
  {B00010011, B100100},
  {B00011111, B111100},
  {B00011111, B110100}
};

If there is no way to mix or map them in a dynamic way so any possible combination between 00 and 99 can be achieved, the only solution is to add vias on the PCB and rewire everything as explained in the datasheet.

Any ideas?

Thanks

The trick here is to employ both a local memory buffer, and digit masking.

Step one: create a pair of masks that define which bits of the memory are associated with which digit.

Imagine you have your digits wired in this order in memory. For simplicity I am working with 16-bit values, but there is no reason why you can't split them into two 8 bit values each if you find that easier (P is the decimal point. Lower case is the left digit, upper case the right digit):

      MSB                         LSB
      a C d g E B p A c D f b e G F P

You would then create a pair of corresponding 16-bit values that represent which bits are associated with each digit.

      MSB                         LSB
      a C d g E B p A c D f b e G F P
Left  1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
Right 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1

The right is just the inverse of the left, so for right you can actually use ~left and save yourself 2 bytes.

So that would end up as:

uint16_t leftDigit = 0xB2B8;
uint16_t rightDigit = 0x4D47;

Now you create yourself a table of which segments create which numbers. Now the magic here is that you don't want individual digits. Not yet. What you want is a table of 16-bit values that represent the numbers 00, 11, 22, 33, 44, 55, 66, 77, 88, 99 (and optionally two spaces, but that's just 0x0000, so you may not need to store that explicitly).

You may end up with something like:

uint16_t digits[] = {
    0b1110110111111010, // 00
    0b0100010010010000, // 11
    0b1011110101011100, // 22
    // ... etc ...
};

Now the real magic happens.

You need a memory buffer that mirrors the contents of your driver memory.  You don't directly modify the driver memory - you modify your memory buffer, and then send both bytes of it to the display driver at once, updating all the segments together.

uint16_t buffer = 0;

Now to set a digit you first need to erase whatever is in the bits that correspond to the digit you want.  Let's say we want to display the number 12.  We'll start with the left digit.

// Step one, erase the left digit
buffer &= ~leftDigit;
// Step two, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[1] & leftDigit);

// Step three, erase the right digit
buffer &= ~rightDigit;
// Step four, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[2] & leftDigit);

That is actually quite a long winded way. But it does allow you to just change one digit without affecting the other.  If you want to just replace the entire content of the display (both digits at once) then you don't need as much work:

buffer = (digits[1] & leftDigit) | (digits[2] & rightDigit);

I'll just dismantle that for you so you can see what it does.

            MSB                         LSB
            a C d g E B p A c D f b e G F P
 digits[1]: 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0
 leftDigit: 1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
       AND: 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 // b and c enabled

 digits[2]: 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 0
rightDigit: 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1
       AND: 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 // A B D E and G enabled

OR of ANDS: 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 // b c A B D E G enabled

And map those segments on to the standard layout of a 7 segment display:

And you form the number 12.

Then you take the buffer value and write it out to your display memory.  You can split the 16 bit value into 8 bit values with bit masking (& 0xFF) and bit shifting (>> 8).

uint8_t b1 = buffer & 0xFF; // Lower byte of memory
uint8_t b2 = (buffer >> 8) & 0xFF; // Upper byte of memory


Multiple variable shared between threads? I got 4 threads running on ESP32 (dual core):

1 thread running on 1st core which is related to the WiFi.
1 thread running on 2nd core which is related to the touchscreen.
1 thread running on 2nd core which is related to the display.
1 thread running on 2nd core which is related to the sensors.

Some of the threads execute almost instantly, while for instance the one handling the sensors can take a few seconds per interaction, and no blocking should occur meanwhile for the rest of the threads.
Anyway, with the growing of the program, a lot of variables started to be involved in data transfers between the cores, and since the whole thing is about to be redone, I have the following questions, to clear the things up for myself, since I found quite a lot of confusing, even contradictory information in examples and explanations on the internet:

Is the "volatile" keyword really sufficient for exchange of data between threads (no ISR)?
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?
What approaches should be used when exchanging a lot of variables between the threads (currently about 40 variables, but the number will probably grow)?
Is xQueueSend / xQueueReceive blocking in case it is put all around the threads with different variables?

Is the "volatile" keyword really sufficient for exchange of data
between threads (no ISR)?

No - "volatile" just tells the compiler that the variable may change value due to something other than the immediate code being generated and informs the code-generator not to rely on the value remaining static when it would otherwise expect so. When copying the value to a register for instance, it would normally expect that register value to continue to represent the value of the variable in memory but if the variable is volatile, that assumption doesn't hold. This would be used to indicate that an ISR might change it at any time; that the variable is an input register and may be changed from the outside at any time; or that another thread may change it, again, at any time (assuming pre-emptive multi-threading or multi-tasking).
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?

No - volatile just describes an attribute about the variable over time

What approaches should be used when exchanging a lot of variables between the threads

Use a semaphore here. A thread that wants access to one of - or the collection of - shared variables asks for the semaphore. The RTOS either returns it immediately, or (because another thread already holds it) suspends the task until it becomes available, and returns it then. The thread holding the semaphore may access the variables (or whatever shared resource this semaphore controls), then returns the semaphore on completion. Semaphores are usually built in to the RTOS.
(As I'm not familiar with your particular RTOS, I'll leave your fourth question for someone who is).


How can I make this code read a page every 10 seconds? I got problems with the code and I have used most of today, trying to find a solution and it's starting to drive my crazy. I hope one of you guys will be able to help me out.

I need the code to check a specific page every 10 seconds, single character.

This is what I have now, working code:
Where should I start?

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();

  Serial.println("connecting ...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    // The code above should run even 10 seconds

  }

  if(!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }

}

Update: Edit the loop like the example below does not work either, it stops after the first loop (8 LOW):

void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    delay(5000);

    // The code above should run even 10 seconds

  }

}

As discussed in the comments, you need to connect to the client each time, not just once.

Here's my modified version of your code, which I hope will work -- I'm not set up to test it.

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();
}

void loop()
{
  // Connect to the server
  Serial.println("connecting ...");

  EthernetClient client;
  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }

  // Wait a moment for data to arrive
  // Note: This is NOT a reliable way of doing it!
  delay(1000);

  if(client.available() > 0) {
    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }
  }

  // Disconnect the client
  if(client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // Wait another 9s, which will give us a delay of roughly 10s
  delay(9000);
}


HX711 sporadic wrong values Am interfacing HX711 with arduino to measure the load of something. However, in my project, I need to continuously monitor the load.

I get fairly accurate values most of the time however, at times I suddenly get a junk value. For example, I call the weight function every 3 seconds and I have placed a 10kg weight, this is what I get. 17.25 is the concern.

10.04, 10.03, 17.25, 10.04, 10.03, 10.03

Am using HX711 library and my process function is a simple call as shown below.

float Processweight()
{
  Serial.print(scale.get_units(40), 2);

  scale.power_down();              // put the ADC in sleep mode
  delay(500);
  scale.power_up();
}

is there something that am missing? What could cause the wrong values?

I get fairly accurate values most of the time however, at times I suddenly get a junk value.

if you use the ebay board, it has the incorrect grounding, which may contribute to the sporadic values you saw.

  For example, I call the weight function every 3 seconds

poor quality libraries could be another possibility.

I have used the board quite extensively and aside from its tempco, it is fairly reliable. you can see here: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

when everything is done right (and in a constant temperature environment), it has very good consistency.


How to read Serial data when multiple functions are Running? I want to halt the execution of that code, when arduino is receiving serial data for the execution. Right now the Serial data runs when the other code has completed its execution. How can I do it ?

void loop() {
    dmd.setBrightness(brighVal); // set the brightness to led matrix
    scroll();  //function to scroll message

}
void serialEvent() {
  while (Serial.available()) {
    Jsondata = Serial.readString(); //reading json data from APP
    DynamicJsonBuffer jsonBuffer;
    Serial.println(Jsondata);
    JsonObject& root = jsonBuffer.parseObject(Jsondata);
    if (root.containsKey("BiM")) {
      brighVal = root["BiM"];
      switch (brighVal) {   // set's the value of brightness according to brighVal
        case 0:
          brighVal = 2;
          break;
        case 1:
          brighVal = 10;
          break;
        case 2 :
          brighVal = 25;
          break;
        case 3 :
          brighVal = 200;
          break;
      }
    }
  }
}
void scroll() {
  dmd.clearScreen( true );
  dmd.selectFont(Arial_Black_16);
  dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
  long start = millis();
  long timer = start;
  boolean ret = false;
  while (!ret) {
    if ((timer + 30) < millis()) {
      ret = dmd.stepMarquee(-1, 0);
      timer = millis();
    }
  }
}

Then let scroll return immediately

void scroll() {
    static long timer = 0;
    static boolean scroll = true;
    if(scroll){
        dmd.clearScreen( true );
        dmd.selectFont(Arial_Black_16);
        dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
        scroll = false;
        timer = millis()
    }else {
        if ((millis() - timer) > 30)  {
            scroll = dmd.stepMarquee(-1, 0);
            timer = millis();
        }
    }
}

The static keyword means that the value of the variable will be kept across calls.

I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.


Arduino Due Port Not Found I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:

    Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.Sketch.upload(Sketch.java:1178)
    at processing.app.Sketch.exportApplet(Sketch.java:1152)
    at processing.app.Sketch.exportApplet(Sketch.java:1124)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
    at processing.app.Serial.touchForCDCReset(Serial.java:87)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
    ... 6 more
Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
    at jssc.SerialPort.openPort(SerialPort.java:167)
    at processing.app.Serial.touchForCDCReset(Serial.java:81)
    ... 7 more
Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Not sure what all that was but a simple restart of my computer seemed to fix it.


Where can I find beginner resources on using voltage regulators with Arduino circuits? I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.

I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics & Arduino. (I'd like to go from there to transistors, mosfets, etc.)

In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.

Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.

It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well.

The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.

Part Number     Output Voltage (V)      Minimum Input Voltage (V)
7805            +5                      7.3
7806            +6                      8.3
7808            +8                      10.5
7809            +9                      11.5
7810            +10                     12.5
7812            +12                     14.6
7815            +15                     17.7
7818            +18                     21.0
7824            +24                     27.1

Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.

Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.


stray \342 in program When I try to compile my code it says "stray '\342' in program

My code:

#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

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

  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop() {
  if (remote.decode(&result)) {
    val = result.value;
    if (val == 0xFFFFFFFF) {
      val = prev;
    }
    prev = val;
    detekceKlaves();

    remote.resume();
  }
}

void detekceKlaves() {

  switch (val, HEX) {

    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");

  }
}

Error code:

Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

irTEST:43:20: error: stray '\342' in program

     case 0x807FB24D:

                    ^

irTEST:43:21: error: stray '\200' in program

     case 0x807FB24D:

                     ^

irTEST:43:22: error: stray '\254' in program

     case 0x807FB24D:

                      ^

irTEST:47:10: error: stray '\342' in program

     case 0x807FB04F:

          ^

irTEST:47:11: error: stray '\200' in program

     case 0x807FB04F:

           ^

irTEST:47:12: error: stray '\255' in program

     case 0x807FB04F:

            ^

irTEST:47:23: error: stray '\342' in program

     case 0x807FB04F:

                       ^

irTEST:47:24: error: stray '\200' in program

     case 0x807FB04F:

                        ^

irTEST:47:25: error: stray '\254' in program

     case 0x807FB04F:

                         ^

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino: In function 'void detekceKlaves()':

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:43:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB24D:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:47:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB04F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:51:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F18E7:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:55:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F906F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:59:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F9867:

     ^~~~

Multiple libraries were found for "IRremote2.h"
 Used: C:\Users\maxim\Documents\Arduino\libraries\IRremote2
exit status 1
stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Please help

If I copy your provided code in a vim-editor you can see some strange characters. <202c>

switch (val, HEX) {
  4
  5     case 0x807FB24D<202c>:
  6       Serial.println("Stisknuto PLAY");
  7       tone(2, fre);
  8       break;
  9     case <202d>0x807FB04F<202c>:

I've removed them for you:

#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

void setup()
{
  Serial.begin(9600);
  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop()
{
  if (remote.decode(&result))
  {
    val = result.value;
    if (val == 0xFFFFFFFF)
    {
      val = prev;
    }
    prev = val;
    detekceKlaves();
    remote.resume();
  }
}

void detekceKlaves()
{
  switch (val, HEX)
  {
    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");
  }
}


Using union to return a range of bits from a data frame: wrong approach? I'm working on an adaptation of Jason Leyrer's Guitar Hero Library for Arduino.  My version is for a DJ Hero controller, and I've also borrowed some code from this Arduino forum thread: topic=120527 (sorry can't post links yet).

The protocol is i2c and I am successfully reading data from it, however I'm not 100% sure what to do with the data.

The buttons are fine, as they are mapped to just one bit in a given byte.  However the other controls are a combination of 4, 5 and 6 bit longs.

The format according to Wiibrew is like so:

BE is for Euphoria button
CS : Crossfade Slider, lower is left and upper is right
SX and SY are the black analog stick.
ED is the Effect Dial
RTT is the turntable on the right as a 6-bit signed integer (positive = CW; negative = CCW)
RBG,RBR,RBB are the Green, Red and Blue buttons on the right
LTT is the turntable on the left as a 6-bit signed integer (positive = CW; negative = CCW)
LBG,LBR,LBB are the Green, Red and Blue buttons on the left

I'm trying to do this:

 signed long DJ_ED()
{
  pack5 ED;
  ED[0] = (DJ_buf[3] >> 5) & 1;
  ED[1] = (DJ_buf[3] >> 6) & 1;
  ED[2] = (DJ_buf[3] >> 7) & 1;
  ED[3] = (DJ_buf[2] >> 5) & 1;
  ED[4] = (DJ_buf[2] >> 6) & 1;

  return ED;
}

Where pack5 is the following:

#define packet5
union pack5
{
   signed long value;
   int ints[5];
};

but I'm getting the following error:

no match for 'operator[]' (operand types are 'pack5' and 'int')

What am I doing wrong?

You are using a union so you have to specify which part of the union you want. Your function should read:

 signed long DJ_ED()
{
  pack5 ED;
  ED.ints[0] = (DJ_buf[3] >> 5) & 1;
  ED.ints[1] = (DJ_buf[3] >> 6) & 1;
  ED.ints[2] = (DJ_buf[3] >> 7) & 1;
  ED.ints[3] = (DJ_buf[2] >> 5) & 1;
  ED.ints[4] = (DJ_buf[2] >> 6) & 1;

  return ED.value;
}

It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.

The code below seems to match the data structure you posted an image of:

struct packedFields
{
  // byte 0
  unsigned int sx      : 5;
  unsigned int rtt_4_3 : 3;

  // byte 1
  unsigned int sy      : 5;
  unsigned int rtt_2_1 : 3;

  // byte 2
  unsigned int rtt_5   : 1;
  unsigned int cs      : 4;
  unsigned int ed_4_3  : 2;
  unsigned int rtt_0   : 1;

  // byte 3
  unsigned int ltt_4_0  : 5;
  unsigned int ed       : 3;

  // byte 4
  unsigned int ltt_5    : 1;
  unsigned int rbr      : 1;
  unsigned int b_plus   : 1;
  unsigned int filler_2 : 1;
  unsigned int b_minus  : 1;
  unsigned int lbr      : 1;
  unsigned int filler_1 : 2;

  // byte 5
  unsigned int filler_4 : 2;
  unsigned int rbb      : 1;
  unsigned int lbg      : 1;
  unsigned int be       : 1;
  unsigned int rbg      : 1;
  unsigned int filler_3 : 1;
  unsigned int lbb      : 1;

};

union packedFieldsUnion
  {
  packedFields a;
  byte b [6];
  };

void doSomethingWithTheFields (packedFieldsUnion & theFields);  // prototype
void doSomethingWithTheFields (packedFieldsUnion & theFields)
  {
  theFields.a.rtt_4_3 = 3;
  theFields.a.ltt_4_0 = 2;
  }  // end of doSomethingWithTheFields

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("packedFields sized = "));
  Serial.println (sizeof (packedFields));

  packedFieldsUnion foo;
  memset (&foo, 0, sizeof foo);

  doSomethingWithTheFields (foo);

  Serial.println (F("-- packedFields bytes --"));
  for (int i = 0; i < sizeof foo; i++)
    Serial.println ((int) foo.b [i], HEX);

  }  // end of setup

void loop ()
  {
  }  // end of loop

I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.

A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.

If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.


GSM arduino to webservice not working I have setup a arduino with a SIM300 based GSM board. I have

Tx of Arduino connected to the Rx of GSM board
Rx of Arduino connected to the Tx of GSM board
Gn of Arduino connected to the Gd of GSM board

The GSM has a Vodafone 3g sim, activated with 3g. The GSM board has 2 LED's, one remains ON and the other blinks ever 4-5 seconds. Which I guess means that its configured to work with the SIM.
I then run the following code.
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  mySerial.begin(9600);

  Serial.println("Serial ports initialized");

   delay(500);
   Serial.println("AT+CGATT=1");
   delay(500);
   Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\",\"0.0.0.0\",0,0");
   delay(500);
   Serial.println("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
   delay(1000);
   Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
   delay(2000);
   Serial.println("AT+CIICR");
   delay(5000);
   Serial.println("AT+CIFSR");
   delay(500);
   Serial.println("AT+CIPSTATUS");
   delay(500);
   Serial.println("AT+CDNSORIP=1");
   delay(500);
   Serial.println("AT+CIPSTART=\"TCP\",\"http://myec2DNS-us-west-2.compute.amazonaws.com:myportnumber/mywebservice/myreques/Authentication/Request?identity=somecode&identityType=sometype\",\"myportnumber\"");
   delay(500);
   Serial.println("AT+CIPSEND");
   delay(500);
   Serial.println("AT");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

On cutecom I get te following
Serial ports initialized
AT+CGATT=1
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET","0.0.0.0",0,0
AT+CDNSCFG="8.8.8.8","8.8.4.4"
AT+CSTT="TATA.DOCOMO.INTERNET","",""
AT+CIICR
AT+CIFSR
AT+CIPSTATUS
AT+CDNSORIP=1
AT+CIPSTART="TCP","http://myec2DNS-us-compute.amazonaws.com:8080/myservice/mycommand/Authentication/Request?identity=%somecode&identityType=1","8080"
AT+CIPSEND
AT

When I run `tail -f  /var/lib/tomcat7/logs/localhost_access_log.2014-09-20.txt' on my webserver, I get nothing from the arduino.
What am I missing here ?

it seems like you are using the wrong serial interface. I see Serial and mySerial.

After mySerial.begin() you write to Serial, not to mySerial which runs on pins 10 and 11.

What's when you send the AT Commands from your Serial connection to the Arduino? It Should redirect them to the GSM board.


The exact time for functions or CPU cycles for any function I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.

The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for ReadParallel and WriteParallel functions (digitalRead, digitalWrite, bitRead,bitWrite) in my code or any other instructions?

Here is the code for the Arduino Uno:

#define InterruptInputPin 2 // For checking if the input data is available
#define InterruptSensorPin 3 // For checking when to send data

#define IN0 A0
#define IN1 A1
#define IN2 A2
#define IN3 A3

#define OUT0 5
#define OUT1 6
#define OUT2 7
#define OUT3 8

volatile int ParallelInput; // The input data

//*************************************
void ReadParallel() //Reads input and saves it in parallelInput.
{
  if (digitalRead(IN0) == HIGH)
    bitWrite(ParallelInput,0,1);
    else
      bitWrite(ParallelInput,0,0);

  if (digitalRead(IN1) == HIGH)
    bitWrite(ParallelInput,1,1);
    else
      bitWrite(ParallelInput,1,0);

  if (digitalRead(IN2) == HIGH)
    bitWrite(ParallelInput,2,1);
    else
      bitWrite(ParallelInput,2,0);

  if (digitalRead(IN3) == HIGH)
    bitWrite(ParallelInput,3,1);
    else
      bitWrite(ParallelInput,3,0);

}
//***************************************

void WriteParallel() //Writes ParallelInput to output.
{
  detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
  digitalWrite(OUT0,bitRead(ParallelInput,0));
  digitalWrite(OUT1,bitRead(ParallelInput,1));
  digitalWrite(OUT2,bitRead(ParallelInput,2));
  digitalWrite(OUT3,bitRead(ParallelInput,3));
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

}

void setup() {

  pinMode(IN0,INPUT);
  pinMode(IN1,INPUT);
  pinMode(IN2,INPUT);
  pinMode(IN3,INPUT);

  pinMode(OUT0,OUTPUT);
  pinMode(OUT1,OUTPUT);
  pinMode(OUT2,OUTPUT);
  pinMode(OUT3,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

}

void loop() {

}

Method summary

(section added on 2018-01-28)

There are several methods available for timing code. I am adding this
preliminary section to my answer in order to provide comparative data on
several methods. The methods covered in the table below are those
proposed as answers to both this question and a duplicate question of
this. As this question has been tagged “arduino-uno”, all
this data assumes an AVR-based board clocked at 16 MHz.

Method comparison:

| method         | resolution    | max. time       | typ. overhead  |
|----------------|---------------|-----------------|----------------|
| `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
| `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
| Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
| pin toggling   | scope-limited | ∞               | 0.125 µs       |
| cycle counting | 0.0625 µs     | boredom-limited | 0              |
| looping        | N.A.          | N.A.            | 0.25 µs        |

The methods are characterized by the following criteria:

Resolution is the granularity of the measurement, the smaller the
better.
Maximum measurable time: any method that does timing arithmetics
on the Arduino is prone to overflows if measuring too long times. Note
that a timer rolling over to zero during the measurement is not a
problem, as long as the period being measured is less than
the rollover period.
Typical measurement overhead: the code used to measure the timings
takes itself a finite time to execute, thus one ends up measuring the
execution time of the “instrumented” code, which is slightly larger
than the time taken by the code one is trying to profile. This
overhead should in principle be subtracted from the result, but it is
often not known exactly, as it depends on how the compiler optimizes
both the instrumented and the non-instrumented code.

The methods listed in the table are:

millis(), which may be the most obvious choice, as it is so well
known. Its low resolution, however, makes it ill-suited for timing
code execution. It should be noted that the millis() counter is
incremented every 1024 µs. Most of the time it is incremented by
1 but, every 43 ms (roughly) it is incremented by 2 in order to
avoid creeping drift. This is why its resolution is stated as
“1 – 2 ms” in the table.
micros(), as proposed in ratchet freak's answer, is usually
a good choice, the main caveat being the 4 µs resolution, when
one could naively expect 1 µs. It also has a significant
overhead.
Timer 1, which is discussed in the second part of this answer, is
my favorite: it has single cycle resolution and low overhead. However,
it is incompatible with other uses of the timer (PWM, Servo
library...). It is also limited to measuring small delays.
Pin toggling, as proposed by 4ilo, and by myself in the third
part of this answer, is ideal if you have an oscilloscope handy. Any
half-decent scope should provide single-cycle resolution. It is also
minimally invasive on the code being measured and has minimal
overhead.
Cycle counting, as proposed in Majenko's answer, is arguably
the “perfect” method: it is cycle-accurate, does not modify the code
and has zero overhead. However, for anything beyond a handful
instructions, it quickly becomes tedious. And it requires some
understanding of the AVR assembly.
Looping, as proposed in Michel Keijzers' answer, is not a
measurement technique per se. It is meant to be used in conjunction
with another technique in order to improve the resolution and dilute
the overhead. However, lopping carries it's own overhead, which is
typically 4 CPU cycles per iteration, assuming a 16-bit loop
counter.

Using Timer 1

(original answer of 2017-10-23)

One technique I often use is to make Timer 1 count at the full CPU speed
and use it to time the code I want to profile. For example:

volatile uint8_t pin = 2;
volatile uint8_t value = HIGH;

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

    // Set Timer 1 to normal mode at F_CPU.
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    cli();
    uint16_t start = TCNT1;
    digitalWrite(pin, value);
    uint16_t finish = TCNT1;
    sei();
    uint16_t overhead = 8;
    uint16_t cycles = finish - start - overhead;
    Serial.print("digitalWrite() took ");
    Serial.print(cycles);
    Serial.println(" CPU cycles.");
}

void loop(){}

Note the volatile variables used to prevent the compiler from
optimizing them as constants.

Note also that when you profile some code you are inevitably slowing it
down, because of the time taken by the profiling operations themselves.
This is what the overhead variable above accounts for. In order to
know the exact overhead, I start with a guess, compile and disassemble,
and then count the number of clock cycles spent in profiling that will
be counted by the timer. Then I adjust the overhead value, compile and
disassemble again, and make sure the overhead has not changed. This is
also when you have to ask yourself what exactly you want to count. Here
I am counting the time needed to execute call digitalWrite, but not
the time needed to get the arguments in the proper registers, as I am
artificially slowing this down by making them volatile.

This method is good for anything that takes more than roughly a dozen,
and less that 65,536 clock cycles. Less than that, clock counting would
be simpler, since you still have to clock-count the overhead. More than
that, the count would overflow, and you could instead just use
micros(), and live with its inherent inaccuracy.

Toggling a pin

(section added on 2017-10-23)

If you have a scope, there is another method that is minimally
invasive on your code: toggle a pin just before and just after the thing
you want to time. E.g., assuming you have previously
pinMode(13, OUTPUT):

// Set pin 13 HIGH.
PORTB |= _BV(PB5);

// The thing we want to time.
...

// Set pin 13 LOW.
PORTB &= ~_BV(PB5);

This will create a pulse that you can measure on the scope. Note that
using direct port access, like here, the overhead is only two CPU cycles,
or 125 ns. Also, direct port access won't use any CPU register, so
chances are the compiler will not generate less efficient code than when
not including the timing part.