is a 5V cellphone power supply stabilised? can I feed my arduino UNO with a 5V cellphone USB power supply ?
Since the arduino board doesn't regulate the 5V from the USB input, is a cellphone power supply sufficiently regulated ?

Yes. USB is a standard. You can even use 5V power packs for portable gizmos.

Caution: Ken Shirrif have a good post about non-original USB chargers and its perils. (A dozen USB chargers in the lab: Apple is very good, but not quite the best). Read them and learn a lot.

I only use the original charger that comes with the cell or tablet (and that usually last longer that the cell or tablet that it comes with). I don't trust any third party USB charger or car adapter after Ken's analysis


Arduino UNO vs NANO or MICRO with RPi3 I'm currently using an Arduino UNO with a raspberry pi 3b. I'm using the USB connector for both power and comms, i.e. the arduino is powered by the RPI via the USB cable, and also i use the same cable for serial communication between the pi and the UNO.

My question is, could i use the same code, and wiring if i were to change the UNO with a NANO or MICRO?

So for example, on the RPI side of things, could i still simply setup the arduino in my python code as

arduino = serial.Serial('/dev/ttyACM0', 9600)

and send commands with something like

arduino.write('2')

and on the arduino side of things, just check if there is serial data coming in and read it, like

if (Serial.available()) {
    command = Serial.read();

I know this may be a very stupid question, but to wrap it up, would anything change other than number of analogues, digitals etc, if i were to switch from an UNO to a MICRO or NANO?

The Nano uses the same chip (ATMEGA 328P) that is on the Uno.  So putting the same code on the Nano should work the same as the Uno.

The Micro uses a different chip.  Whether or not the code from your Uno will work on your Micro depends on what is in the code.  You chose not to show anyone the code so that can't be answered yet.


What should I do to communicate with GSM module? Sorry, im a beginner, i tried to program an automatic doorlock using sms. But, I dont understand what happen with this error, what should I do? Add library? The error said that Pstring wasnt declared, but i dont know how to declare this.

#include <LiquidCrystal.h>
#include "SIM900.h"
#include "sms.h"
#include "SoftwareSerial.h"
#include "sms.h"

SMSGSM sms;
boolean started=false;
char buffer[160];
char smsbuffer[160];
char n[20];
int pintu=5;
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50;
boolean st=false;
int buzzer=6;

void setup()
{
  pinMode(pintu,OUTPUT);
  pinMode(buzzer,OUTPUT);

  digitalWrite(pintu,LOW);
 if (gsm.begin(9600))
 {
  started=true;
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
  }
   if(started)
  {
   delsms();
   sms.SendSMS("08970869443","Pintu SMS Menyala");
  }
  else{digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(buzzer,LOW);
  }

   }

   void loop()
   {

   int pos=0;
  if (gsm.begin(9600))
  {
  if (started){
  pos=sms.IsSMSPresent(SMS_ALL);
  if(pos)
  {
   sms.GetSMS(pos,n,smsbuffer,100);
   delay(2000);
    if(!strcmp(smsbuffer,"bukapintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Pintu Dibuka");
    digitalWrite(pintu,HIGH);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    if(!strcmp(smsbuffer,"tutuppintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Kunci Pintu Ditutup");
    digitalWrite(pintu,LOW);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    delsms();
   }
   }
   }
   }

   void delsms()
   {
   for (int i=0; i<10; i++)
  {
     int pos=sms.IsSMSPresent(SMS_ALL);
    if (pos!=0)
   {
    if (sms.DeleteSMS(pos)==1){}else{}
   }
   }
   }

Error message :

     Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

      D:\Kuliah\Project\Skripsi\pintu_sms\pintu_sms.ino: In function 'void loop()':

      pintu_sms:67: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

      pintu_sms:67: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:68: error: 'str' was not declared in this scope

     str.begin();

     ^

    pintu_sms:76: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

    pintu_sms:76: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:77: error: 'str' was not declared in this scope

     str.begin();

     ^

     exit status 1
  'PString' was not declared in this scope

The compiler does not know what PString is. It is not declared in any of the libraries you have included.

You could rewrite to something like this.

strcat(buffer, "Pintu Dibuka");
n = strlen(buffer);
digitalWrite(pintu,HIGH);
sms.SendSMS(n,buffer);

Please change the other block in the same way.

There are more errors. You also need to change "int n[20]" to "int n".

That is a good start.

Cheers!


Motor not switching with 2N3904 I have a small motor, it powers fine from the 3V3 and GND output of the arduino nano ble 33. However I need to be able to switch it on and off. My first attempt was to use an output pin, but that doesn't supply enough power. I'm trying to use a 2N3904 transistor (my first time attempting to use one, so sorry if I've done something stupid). I've tried wiring it as follows, but no luck:

Is this possible, or do I need something more substantial like a reed switch?

1st : you have to put an appropriate resistor between the output of your arduino and transistor Base pin

2nd : you have to connect you motor and biased transistor to >>>> a suitable power supply (which has enough current (Amps) on it's output)

you can use this circuit instead of yours :

3rd : don't forget to use the diode in the schematic; it protects transistors from you motor coil's spikes you can use 1n4147 ( it depends on the size of your motor but i think, it works for you ( i wasn't successful to take a look at your motor and it's specifications )

4th : ignore the number of transistor, you can use your transistor (2N3904) instead of it

5th :NOTICE : this circuit has a problem, you have to connect appropriate power supply and replace "arduino 5 volts" by the + of your power supply in this circuit schematic

good luck


Linking Arduino Nano with ESP8266 Wifi module I recently started playing around with Arduinos to connect a few sensors up. I used an Arduino Nano to measure temperature, humidity, air pressure and light level.

To store the data in a database, I used another Arduino that I connected to a Raspberry Pi, and let the two Arduinos talk wirelessly to each other via 433 MHz.

That all works pretty well, but the 433 MHz communication is not exactly the most reliable (I often miss a transmission). When I stumbled upon the ESP8266 module, it seemed like the optimal solution for communication. How cool would it be if I could just pull out the information via an HTTP call from the Raspberry Pi?

After toying around for many hours, uploading many different firmwares, getting more and more frustrated because I could not get it to do anything, I finally have it working through an FTDI module connected up like this:

I use an MB102 power module to provide the 3.3v required by the ESP8266. I turns out you need to connect the ground from the MB102 to the ground of the FTDI module to get any proper response. After doing that I was able to send AT commands and get the proper responses. I could even connect it to my home Wifi.

The next thing I want to do is connect it to the Arduino. I found a very simple schema for that (http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/), where you connect RX to TX and TX to RX. Using the MB102 I connected it like this:

Apparently I should now be able to upload a blank sketch to the Arduino, and then use the serial monitor again to sens AT command, exactly the same way I did it when using the FTDI module.

The problem is that I get nothing at all this way. I don't even see my own AT commands in the console. I do see the ESP8266 flashing every time I send a command (I even see it it still connected to my router, probably it remembered the info I send through the FTDI...?)

The question is, what am I going wrong? I read some posts about the TX from the Arduino also being 5v and that you need to do something to bring it back to 3.3v, but there are also many tutorials that say it's not required.

The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.

Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):

# To configure a new ESP module:
# Connect the ESP and the FTDI as in your top diagram, set your
# terminal-emulator to 115200 baud, and enter the following:

AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

# Now change the terminal emulator baud rate to 9600

AT+CWMODE=1                    # Set ESP to station mode (client)
ATE0                           # Set ESP's echo off
AT+CWLAP                       # List access points - after a short pause
                               # the ESP returns a list of WiFi access points

For future reference, here is a link to the ESP8266 AT Instruction Set.

Update June 2020: The above link was broken, now fixed. You can also find documentation at Espressif's github account (online readable, but not pdf, as of this date).


Is it bad practice to multitask without timing constraints Going through resources such as several things at the same time and with some greatly appreciated assistance on here I'm finally getting a grasp on how to multitask a microcontroller.
Most examples use the millis() approach to nonblocking programming. However, even in the link above the button state is being polled every loop (from what I understood).
So what confuses me is: is it bad practice to write functions, which poll sensor(s) and input(s) without timing constraints, i.e. at every iteration of loop?
Is this still consider nonblocking programming?
I've written some mock code to better illustrate what I mean. Thank you very much for reading through.
void loop() {
    Button();
    Sensor();
    LED();
    // ...
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state == LOW) {
    // ...
  };
};

void Sensor() {
  // Read sensor
  int sensor_state = analogRead(sensor_pin);
  if (sensor_state >= 150) {
    // ...
  };
};

Like often, the answer is: It depends.
Generally it is non-blocking programming, when you do only short things on each loop. What exactly can be considered short depends on the situation, meaning, what else you want to do.
For example: You are reading an analog value on every loop. The analogRead() will take about 100us (reference). I assume, that your sensor value is rather slow (so the time of signal above 150 would be rather long). Also you are reading a button with digitalRead(). The read takes about 3.6us (reference). So in total you have a loop of - lets say - 150us (with overhead and loop() iteration included). But the event, that you want to catch - the button press - will be in the ballpark of 100ms, which is a factor 667 greater, than the total time of your loop() (when no event happened). So in relation to the shortest event (the button press) all the reads can be considered non-blocking. (Though you could still get blocking through the code inside the if statements. Thats on you to investigate)
Non assume, that you don't have a button, but a digital signal, and you want to sense pulses down to 80us. Then your analogRead() would take too long and you could miss a pulse event. In this case analogRead() might be considered blocking.
So, to check if you are really using non-blocking code, you would need to ask yourself: Am I giving every code part enough time to execute right and to catch all the intended events? If yes, then you are non-blocking. If no, then you are blocking.

As a side note: Often polling is described as bad, but it really depends on the situation. In your case you poll the inputs sequentially, so every input gets polled at the same (total) rate at which your loop() runs. You are doing nothing else, so why should you lower the processing time by not use polling? The saved time cannot be used better on a microcontroller (in contrast to a PC, where the saved CPU time could be given to a different program).


Extra characters remain in Serial I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.

Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.

As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.

I have tried different ways to solve this problem, but unfortunately I cannot find the solution.

Here are my functions used for communication:

void sendCommandToSerial(int command) {
  Serial3.print(command);
  Serial3.print(TERMINATOR_CHAR);
  Serial3.flush();
}

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

int readRawBytes(char *inputBuffer,const int bufferSize) {
  return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
}
int readIntFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atoi(inputBuffer);
  }
  return -1;
}
int readFloatFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atof(inputBuffer);
  }
  return -1;
}

I have tried both software and hardware serials, still the same.
Please help to find and solve the problem.

The Stream member function readBytesUntil() does not null terminate the string. It returns the number of characters read. You must terminate the string with null(0) before calling atoi() and atof() or fill the string will null(0) before calling readBytesUntil().

For more details see Arduino Stream.cpp.

Cheers!


Get a LED to fade out I want to light an LED in a sketch and then have it fade out.
I tried to use analogWrite and have it decrease from a value of 255 to 0 using a for() loop, but I can't seem to get it to work.
Using digitalWrite I can turn it on and off but cant get it to fade out.
Can anyone help please.

const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 9;
int j = 0;

void setup() {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
}

void loop() {
    j = 255;
    delay(1000);
    if (j >= 5);
    {
        analogWrite(ledPin3,j);
        delay(10);
        j = j - 5;
    }
    delay(1000);
}

Not all output pins are able to perform PWM ("AnalogWrite").

  On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

https://www.arduino.cc/en/Reference/AnalogWrite

Note that the PWM-enabled ports are marked by a "~" on the board.

If you try analogWrite, e.g., on port 4, you'll get your observed switch behaviour.


Flashing a ATmega328 that came from an Arduino to not use an external oscillator I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.

This image has this caption.

  Because no external clock source is connected, the ATmega must be configured to use its internal clock.

I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator.

So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?

» avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.

Pick up a 8-16MHz crystal (not an oscillator) and two 15pF capacitors and use very, very short wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.


Calling external function from a class function I'll try to explain my need:

I have a generic library I created, called myIOT.h.
This class have a pre-configured  MQTT and wifi setup.
Inside this library there is a mqtt_callback function, for all generic commands, such as boot_time and connection_status.
BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that iot.mqtt_callback(ext_mqtt_func) will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:

void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something

};

else {

ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

}

Yes, you can do it.

You pass function pointer as function parameter.

See this stackoverflow question:

https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter


Executing multiple functions/commands on Arduino I am using an RFduino and an iOS application to control some RGB LEDs.

This is how I'm sending a string command to the module:

- (IBAction)fadeButtonPressed:(id)sender {
    [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}

These command(s) are coming back just fine on the RFduino side:

void RFduinoBLE_onReceive(char *data, int len) {
  if (strncmp(data, "fade", 4) == 0) {
    // begin fading chosen LED colour
  }
}

Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.

Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used strncmp(data, "fade", 4) instead of strcmp(data, "fade") and this fixed the issue.

I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.

The functions I would like to be able to do would be controlling of the RGB colours and then Fading or Blinking that particular chosen colour.

What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?

The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (command 0).

Here is my entire sketch so far:

#include <RFduinoBLE.h>

// Pin 2 on the RGB LED.
int rgb2_pin = 2; // red
int rgb3_pin = 3; // green
int rgb4_pin = 4; // blue
int brightness = 0;
int fadeAmount = 5;

// Command properties.
int command = 0;

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // Setup the LEDs for output.
  pinMode(rgb2_pin, OUTPUT);
  pinMode(rgb3_pin, OUTPUT);
  pinMode(rgb4_pin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop() {
  if (command == 1) { // Fade in/out chosen colour.
    analogWrite(rgb2_pin, brightness);
    analogWrite(rgb3_pin, brightness);
    analogWrite(rgb4_pin, brightness);

    // Change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // Reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }

    // Wait for 30 milliseconds to see the dimming effect
    delay(30);
  } else if (command == 2) { // Blink
    digitalWrite(rgb2_pin, HIGH);
    digitalWrite(rgb3_pin, HIGH);
    digitalWrite(rgb4_pin, HIGH);
    delay(200);
    digitalWrite(rgb2_pin, LOW);
    digitalWrite(rgb3_pin, LOW);
    digitalWrite(rgb4_pin, LOW);
    delay(200);
  }
}

void RFduinoBLE_onConnect() {}

void RFduinoBLE_onDisconnect() {}

void RFduinoBLE_onReceive(char *data, int len) {
  Serial.println(data);

  // Each transmission should contain an RGB triple.
  if (strncmp(data, "fade", 4) == 0) {
    command = 1;
  } else if (strncmp(data, "blink", 5) == 0) {
    command = 2;
  } else { // Change colour.
    // Reset other functions.
    command = 0;

    if (len >= 3) {
      // Get the RGB values.
      uint8_t red = data[0];
      uint8_t green = data[1];
      uint8_t blue = data[2];

      // Set PWM for each LED.
      analogWrite(rgb2_pin, red);
      analogWrite(rgb3_pin, green);
      analogWrite(rgb4_pin, blue);
    }
  }

  Serial.println(command);
}

Ended up going with something like this:

#include <RFduinoBLE.h>

// State properties.
int state = 1;
char command;
String hexstring;

// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;

// Setup function to set RGB pins to OUTPUT pins.
void setup () {
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.deviceName = "iOS";
  RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  RFduinoBLE.txPowerLevel = -20;
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop () {
  switch (command) {
    case 1:
      // Blink.
    break;
    case 2:
      // Fade.
    break;
  }

  //RFduino_ULPDelay(INFINITE);
}

// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
  if (c >= '0' && c <= '9') return (byte)(c - '0');
  else return (byte)(c - 'a' + 10);
}

// Process each function/command.
void processCommand (int command, String hex) {
  switch (command) {
    case 'b':
      command = 1; // Set blink mode.
    break;
    case 'f':
      command = 2; // Set fade mode.
    break;
    case 'c':
      // We put together 2 characters as is
      // done with HEX notation and set the color.
      byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
      byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
      byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);

      // Set the color.
      setColor (red, green, blue);
    break;
  }
}

// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
  analogWrite(redPin, red);
  analogWrite(grnPin, green);
  analogWrite(bluPin, blue);
  delay(200);
}

// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
  for (int i = 0; i < len; i++) {
    stateMachine(data[i]);
  }
}

// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
  switch (state) {
    case 1:
      if (data == 1) {
        state = 2;
      }
    break;
    case 2:
      if (data == 'b' || data == 'f' || data == 'c') {
        command = data;
        hexstring = "";
        state = 3;
      } else if (data != 1) { // Stay in state 2 if we received another 0x01.
        state = 1;
      }
    break;
    case 3:
      if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
        hexstring = hexstring + data;
        if (hexstring.length() == 6) {
          state = 4;
        }
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
    case 4:
      if (data == 3) {
        processCommand(command, hexstring);
        state = 1;
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
  }
}


Array values won't tokenize char *p = I2CinBuffer; // array contains "string" "," "string"

but

char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
char *str;       // Temp store for each data chunk
int count = 0;

while ((str = strtok_r(p, ",", &p)) != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
}

does not enter while loop.

Many thanks but the hard coding of the values "6,100" give correct results as it stands. However, I am now aware that the Arduino code is working in C strings and I2CInBuffer is a C string on which the "strtok" or "strok_r" functions will NOT work. My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

You're not using strtok_r properly.  You have to treat the first call to strtok_r differently to all subsequent calls, and I don't know what you're trying to do with the &p parameter - that could never work since you're breaking the source pointer with that.

According to the manual page:

  The strtok_r() function is a reentrant version strtok().  The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

  On  the  first  call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored.  In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Unless you're doing concurrent tokenising of multiple strings there is no reason to use the reentrant version of strtok.  Instead you should just go:

char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;

char *str = strtok(p, ",");
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",");
}

Note how the first call, outside the while loop, passes the string to parse.  All subsequent calls (inside the while loop) pass NULL as the string to parse so it continues from the last point in the string rather than starting the string afresh every time from the start (with a broken string since strtok() is a destructive function).

  A sequence of calls to strtok() that operate on the same string maintains a pointer that determines the point from which to start searching for the  next token.   The  first  call  to strtok() sets this pointer to point to the first byte of the string.  The start of the next token is determined by scanning forward for the next nondelimiter byte in str.  If such a byte is found, it is taken as the start of the next token.  If no  such  byte  is  found,  then there are no more tokens, and strtok() returns NULL.  (A string that is empty or that contains only delimiters will thus cause strtok() to return NULL on the first call.)

It is considered destructive because:

  The end of each token is found by scanning forward until either the next delimiter byte is found or until the terminating null  byte  ('\0')  is  encountered.   If  a  delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; that pointer will be used as the starting point when searching for the next token.  In this case, strtok() returns a pointer to the  start  of  the found token.

So in other words, your string that started out as:

foo,bar,baz\0

ends up, after tokenizing, as:

foo\0bar\0baz\0

So after the first tokenizing, if you try and pass the string again as the first parameter, instead of "foo,bar,baz", it actually only sees "foo" since the string now ends after foo.

If you wanted to use the reentrant version you'd need to create a separate pointer variable for the save pointer and pass that as the third argument:

char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;
char *saveptr;

char *str = strtok_r(p, ",", &saveptr);
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",", &saveptr);
}

Note that you still need to use the same "pass the string on the first call and pass NULL on all other calls" methodology since it is still destructive.


Going from one shift register to two shift registers I am able to control one shift register with this shift function:

void shift (int pin) {
  shiftOut(ds,shcp,MSBFIRST,pin);
  digitalWrite(stcp,HIGH);
  delay(100);
  digitalWrite(stcp,LOW);
}

but when I move to 2 shift registers it does not add up.. how do I need to adapt this method to make it work with 2 shift registers when I am going from 8 leds to 16 leds?

My second register now just copies the first register.. I want the second register to continue instead of repeat

It sounds like the primary issue is how you've connected the two shift registers.  You just need the bit shifting out of the first one to shift into the second one so they act, together, as one longer shift register.

The example pictured is described in full here, under the heading "Example 2":
http://arduino.cc/en/tutorial/ShiftOut

As Klaus mentioned, you want to first ShiftOut the byte you intend to wind up in the second resister, then ShiftOut the byte for the first register.  This will push your first byte through to the second register.


Can I control solid state relay directly from arduino digital pin? I want to switch on/off some AC device using solid state Omron G3MB relay
I know that for magnetic relay there should be transistor and flyback diode, but what about SSR?
Can I connect it directly to arduino digital pin without any transistors and anything else?
In a closer look on special arduino module, we can see some extras. Are they necessary? I want to put solid state relay (not separated module) into my custom PCB, and I'm confused about that extras.

According to the datasheet there are multiple models.
Some already have an input resistor for the led (in the opto-isolator) inside the package, but some don't. For the ones that don't have a resistor inside, you'd need to add one yourself, to limit the current to around 10mA.
Some models also have a snubber circuit inside the package. The need for this depends on what kind of load is connected (inductive vs. resistive (AFAIK)).
I thinks the green thing, in the picture, is a fuse. On the other side of the SSR you can see and indicator led, transistor, and 3 resistor (one to limit current to the SSR, one to limit the current through the indicator led, and on for the base of the transistor.). They probably use a transistor, because the current for the SSR and the indicator led combined, is to high for certain micro controllers.


Long term connection between Arduino and computer I am looking to make indicator lights for my computer to indicate things such as system load, IO usage, et cetera, using an Arduino and NeoPixels.  I would like to just plug it into my computer, and have some custom software connect to it and send it the data it needs as my computer runs.

The part I am having trouble with is figuring out how to connect the Arduino to the computer in a way that is consistent in the long term.

I have had issues with the Arduino switching which /dev/ttyAMC* port it is assigned, so I looked for options other than the USB serial.  The only other way seems to be USB, as that is the only common general purpose port these days.

This is where my problem lies.  People don't seem to be doing this sort of thing, or at least they don't post about it.

The Teensy can act as a USB HID, but the raw HID feature hasn't been updated in almost a decade, the host side code is based on deprecated libraries, and it seems oriented more for Teensy to computer transfers.

There doesn't seem to be any consumer level USB interface chips available, either.

I found V-USB, which seems like a solution to my problems, in fact someone even used it to do basically what I want to do.  However, I would still need to learn the library.

So, my question is what is the recommended way of interfacing between a computer and Arduino in the long term?  Is USB support really necessary, or have I just overthought the entire thing?

I think the easiest option may be to keep the USB (ACM) link, so you
don't have to do anything special on the Arduino, and try to figure out
a way to identify the correct device on the computer side.

On Linux, providing consistent device names for specific peripherals is
normally the job of udev. You could add your own udev rule to create a
symbolic link for your Arduino every time you plug it in. Then, your
custom software would always open /dev/neopixel-monitor, which would
be a symlink to the proper /dev/ttyACMx device.

Actually, you may not need write your own rule. I took a look at the
udev rules installed by default on my Ubuntu 16.04 and found a file
named /lib/udev/rules.d/60-serial.rules meant to populate the
/dev/serial/by-path/ and /dev/serial/by-id/ directories. Then I
plugged in my Arduino Uno R3 and saw the symlink
/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00
automatically created, which right now points to ../../ttyACM0. In
this name, 0043 is the USB device ID of the Uno, and the following
alphanumeric sequence looks like a serial number. The if00 looks like
an interface number, and may vary (it won't, se Majenko's comment).
The link name should
be a good way to uniquely identify that particular Arduino.


How do I program the Arduino Primo Core using the Arduino Primo? the Arduino Primo Core website (https://store.arduino.cc/usa/arduino-primo-core) says that I can program the Arduino Primo Core using an Arduino Primo.

I have no idea how to do this!

Can you do it through the Arduino IDE? Which pins on the Arduino Primo Core should I connect to which pins on the Arduino Primo?

Thanks for your help!

instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads)
Arduino.org pages in web archive


Arduino Yun does it have a RTC? Does the Arduino Yun does it have a RTC?

And if so is it connected to the Atheros AR9331 or the ATmega32u4?

If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

the Yún doesn’t have a real time clock IC on board, so it can’t keep time when is powered off. Instead, it synchronizes with time servers automatically when it powers up and connects to a network using NTP.

(Arduino Blog)

Therefore, the Yun does not have a onboard RTC.

  If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

Probably not. It comes in a LPCC package, which has the solder joints on the bottom. This needs to be soldered by reflow. The Yun does not have any pins connected directly to that chip. You're probably thinking of the ATmega32u4, the actual Arduino chip. The other one is for a router.

To get the time, you have two options:

Use the time from the time server

A few notes:

  The Yún must be connected to a network to get the correct time. If you used the web-based WiFi interface to configure the Yún for the network, make sure you've selected the proper time zone.

Connect it to a DS1307 (I find this Adafruit tutorial helpful) You'll need only two pins to use this board. One note: there is a way to connect up to 121 I2C devices using these two pins. However, that gets a little more complicated.


How to connect Arduino with ESP8266-11 WiFi module to 000webhost (free webhosting) I want to know how to connect my Arduino to my website on 000webhost.com (free webhosting account). I'm using ESP-11 WiFi module and it is connected to the internet.

This is my Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial ESP11 = SoftwareSerial(10,11); // RX, TX
#define DEBUG true

// WIFI SHIELD DECLARATION
String ssid = "\"SampleSSID\"";
String pass = "\"SamplePass\"";
String tcp = "\"TCP\"";
String remoteip = "\"jvystocksystem.000webhostapp.com\"";
String portnum = "80";

void setup(){
  ESP11.begin(9600);
  Serial.begin(9600);
  sendData("AT+CWMODE=1\r\n",2000,DEBUG); // configure as access point and Client
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+GMR\r\n",2000,DEBUG); // View version Info
  sendData("AT+CWLAP\r\n",5000,DEBUG); // List all available AP's*/
  sendData("AT+CWJAP=" + ssid + "," + pass + "\r\n",10000,DEBUG); // Connect to AP
  sendData("AT+CIFSR\r\n",2000,DEBUG); // get ip address
  sendData("AT+CIPMUX=0\r\n",2000,DEBUG); //Single TCP Connections
  sendData("AT+CIPSTART="+ tcp +"," + remoteip + "," + portnum + "\r\n",3000,DEBUG); // Start connecting to localhost <link id>,<type>,<remote IP>,<Port Number>

  String getStr = "GET /getCpno.php?user_type=admin HTTP/1.0"; // Getting info from my online database through my online website
  getStr += "\r\n\r\n";
  String cmd;
  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  sendData(cmd + "\r\n",1000,DEBUG);
  sendData(getStr,3000,DEBUG);
}

void loop() {
  // put your main code here, to run repeatedly:
// For ESP8266
  if(ESP11.available()) // check if the esp is sending a message
  {

    if(ESP11.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = ESP11.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     ESP11.find("pin="); // advance cursor to "pin="

     int pinNumber = (ESP11.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += (ESP11.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/

String sendData(String command, const int timeout, boolean debug)
{

    String response = ""; // ESP8266 sendData String
    ESP11.print(command); // send the read character to the esp8266

    long int time = millis();

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

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

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

    }
    return response;
}

But my code is not returning the value I want from the database, instead I'm getting this in my serial monitor:

I hope you guys can help me with my code.

The web server is using virtual hosts. Unless you tell it to which virtual host are you making a request, the server won't know where to send the request and generate an error.

You need to add the required header Host, which tell it just that.

Make the proper request like this:

String getStr = "GET /getCpno.php?user_type=admin HTTP/1.1\r\n";
getStr += "Host: jvystocksystem.000webhostapp.com\r\n"; // add the required header
getStr += "\r\n";


Specific formatting of floats and converting them to an array of chars I have an oled display which can only display 4 digits + decimal point.
I need a way to format the number into 4 significant figures;
Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.

Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

Normally sprintf() would be the solution - however the sprintf() in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use dtostrf() to get the job done:

dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via String (although I would never recommend using String for anything, ever):

String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.


Serial available doesn't work right after upload I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.

I'm having an issue where whenever I upload the arduino program and try to run the python code the arduino code wouldn't detect serial available on the first run.  I would have to either

open and close serial monitor before I run python program
run the python program, quit, and run it again

and it would continue to work until I re-upload the arduino then the same thing happens.  Does anyone know what is the issue?  This is on Ubuntu.

arduino

String str;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

Python

import serial

ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.

The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured not to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.

The second issue is with the PC side code:

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Assuming that import serial refers to pySerial, then because you did not specify a timeout when opening the port, the ser.readline() is an eternally blocking read.  To quote the documentation:

  Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino.  Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet.  Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.

Your programs are thus stuck in a "no, after you" deadlock.

There are many potential ways to work around this.  For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.

Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.


Time Library Adjust Default on Windows Looking at this Time Arduino library because I would like to send time stamps with data across my HC05-PC channel.

https://playground.arduino.cc/Code/Time

I wrote this function to get the time at any point

String getTime() {
    String timeSecond = String(second());
    String timeMinute = String(minute());
    String timeHour = String(hour());
    String timeDay = String(day());
    String timeMonth = String(month());
    String timeYear = String(year());

    String now = timeHour + ":" + timeMinute + ":" + timeSecond + " " +
        timeMonth + "/" + timeDay + "/" + timeYear;

    return now;
}

It seems in the docs he provides info on how to set the default time on a Linux/Unix system so that this library will always be grabbing the correct time by editing some bash files.

When I run the function, having been compiled on Windows, it begins running on 1/1/1970 0:0:0.

He does not provide any documentation for setting the Windows time stamp. How would I go about doing that?

The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.

If you use a Arduino Due or Zero or M0 then they have their own rtc library.

If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.

What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.

It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.


How can a 5v Uno talk to a 3.3v Due? I currently have an Uno (which operates at 5v), and I'm looking at buying a Due (which only operates at 3.3v). I'd like to make them communicate via Serial or SPI or similar, but presumably connecting them directly isn't an option (I guess the Due's pins would get damaged).

Is there any way to make the connection safe? Or is there an alternative form of communication I could safely use between them instead?

For a 5V logic output to a 3V3 logic input, you can use a resistive divider to lower the voltage.
When unloaded, a 3V3 logic output is just enough to drive a 5V logic input. Check the AVR datasheet for the exact voltages (0.6 × Vcc = 3V, found under DC Characteristics in the datasheet).

In other words, with a little bit of special care it may just work.

To construct a more reliable and bidirectional solution, use a level shifter. There are several listed on this page but other manufacturers make similar devices.

This document describes how a MOSFET can be used to bidirectionally convert logic levels between different supply voltages.


Data type explanation regarding analogRead of a photoresistor This is a fundamental question - very new (1st post) and trying to learn.  I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1.  In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range.  Where should I be looking to understand this behavior?

You should keep it uint16_t.
See: analogRead.
It shows the return value is a 10 bit number, which means a value of 0 to 1023.
If you use uint8_t, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.
With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the analogRead function.
Example
Assume the value is 1000, which is in binary:
11 1110 1000

Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:
0000 0011 1110 1000

However, if you try to store this in 8 bits (using uint8_t) you get:
(removed) 1110 1000

Which is the value 232 instead of 1000.
Some guidelines:

Always use a type that fits the value you want to store (in worst case).
If you know for sure your value will be non-negative, use an unsigned type (e.g. uint8_t).
If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use uint32_t).


Servo start to turn like madman with simple if statement I tried to write a simple program. Press button 1 servo goes to position 1, press button 2 servo goes to position 2.

But when I hook everything up my Servo goes full Crazy mode. It starts to jiggle back and forth like a madman. Even when I unhook the buttons.

What is the mistake I made? Any help is appreciated :D

Thanks in advance

/* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep

    modified 5-12-2017
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);         // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == HIGH) {
    myservo.write(173);        // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == HIGH) {
    myservo.write(97);         // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
}

Please, connect the buttons to the ground and change the code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == LOW) {
    myservo.write(173);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == LOW) {
    myservo.write(97);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
}

Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.


Trouble with Arduino Nano Every and radio transmission using RH_RF69.h I give some help for students working on the Cansat Contest.
I am trying to connect a RFM69 Radio Module to an Arduino Nano Every.
Nothing works : compiling the simpliest program:
#include <RH_RF69.h>

void setup() {}

void loop() {}

gives the answer:
[BlaBlaBla...]
exit status 1
Erreur de compilation pour la carte Arduino Nano Every

while everythings works on arduino M0 Feather Express or Arduino Uno.
Is there a specific problem with the Nano Every?
Thank you for your help.
Jean-Luc Ottinger

The Nano Every uses an ATMega4809 processor, so it is different from most Arduino's. It could well be that it isn't supported by the Radiohead library.
The error you shortened to [BlaBlaBla...] could possibly give more information on that.
A full list of what is supported by the Radiohead library is here; you should check if the Arduino Nano Every or the ATMega4809 is on there; alternatively, all the #defines for the supported boards are in the header file.
If it turns out your board is not supported, you could ask the library's authors if they would consider supporting it, or you could use a different board (it should work with an Arduino Nano 33 IoT, I think, but please check first).


Arduino voltage connection pins On the Arduino power connector jack, which is the positive terminal pin and the negative pin?

Arduino's power connector jack's tip is positive while the sleeve is negative but the more important thing to know is what will you be using in powering Arduino? Please provide more information about your setup and possibly a schematic. This will help us understand more what you're trying to accomplish.


Need help debugging my Binary Clock I have tried everything but I can't get my binary clock to display correctly. The diagram and code are here: Binary Clock | Electronics Lab.

The hardware is based off this (it also explains the process that my program is trying to do): DIY: Binary Clock with Arduino. The problems lie in a, probably, simple error as my variable tempTime, which is used to convert the individual digits to their binary equivalent, does not change when I tell it to. All this occurs in the display function. (Sorry, I'm new Here and only a high school student)

While debugging it I realized that the only problem is the variable tempTime - the hardware and other functions work as they were intended.
Can anyone help? (Sorry if this is not very well documented).

    int digitPins[4][4] = {{13,6,-1,-1},{12,7,3,1},{11,8,4,-1},{10,9,5,2}};
int time[4] = {0,0,0,0};
int steps[4]={1,2,4,8};
int tempTime = 0;
void setup(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    pinMode(digitPins[x][y],OUTPUT);
    }
  }
    Serial.begin(9600);
    convertHour(12);
    convertMinute(57);
    Serial.println("The time is:");

  for(int z = 0; z < 4; z++){
    if(z == 2){
    Serial.print(":");
    }
  Serial.print(time[z]);
  }
  display();
}
void loop(){

}
void display(){
  int displayer[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
/*
0 - Hour
1 - Hour
2 - Minute
3 - Minute
4 - Hour(Total)
5 - Minute(Total)
*/

  int counter1 = 0;
  for(int i = 0; i < 4; i++){ //Loop for the individual digits
    tempTime = time[i];
    if(tempTime >= 10){
    tempTime = tempTime % 10;
    }
    Serial.print("\nBegining new iteration i = ");
    Serial.print("\nStarting with digit: ");
    Serial.print(tempTime);
    Serial.print(i);
    Serial.println("");
    for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
      if(time[i]/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
        Serial.print("\n");
        Serial.print(time[i]);
        Serial.print("/");
        Serial.print(steps[j]);
        Serial.print(" = ");
        Serial.print(time[i]/steps[j]);
        tempTime =tempTime - (time[i]*steps[j]);
        displayer[counter1] = digitPins[i][j];
        Serial.print("\nAdded: ");
        Serial.print(digitPins[i][j]);
        counter1++;
      }
    }

  }
  clear();
  for(int a = 0; a < 13; a++){
  digitalWrite(displayer[a],HIGH);
  }
}
void clear(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    digitalWrite(digitPins[x][y],LOW);
    }
  }
}
  void convertHour(int value){
    int digits[] = {0,0};
    if(value >= 10){
        debug("Bigger than 10");
        if(value >= 20){
            digits[0] = 2;
        }else{
            digits[0] = 1;
        }
    }
    digits[1] = value - (digits[0] * 10);
    //String hour = digits[0]+""+digits[1];
    //Serial.print(digits[0]);
    //Serial.print(digits[1]);
    time[0] = digits[0];
    time[1] = digits[1];
  }
void convertMinute(int value){
  int digits[2] = {0,0};
  int val = value;
  if(value >= 10){
    digits[0] = val/10;
  }
  digits[1] = value - (digits[0] * 10);
  Serial.print("\n");
  Serial.print(digits[0]);
  Serial.print(digits[1]);
  time[2] = digits[0];
  time[3] = digits[1];
}
  void debug(String value){
    boolean de = true;
    if(de){
    Serial.println(value);
    }
  }

In your “Loop to determin the arrangement”, you are erroneously using
time[i] in several places where you mean tempTime. Also, to update
tempTime you only have to subtract steps[j]. With these fixes, your
loop becomes:

for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
  if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
    Serial.print("\n");
    Serial.print(tempTime);
    Serial.print("/");
    Serial.print(steps[j]);
    Serial.print(" = ");
    Serial.print(tempTime/steps[j]);
    tempTime = tempTime - steps[j];
    displayer[counter1] = digitPins[i][j];
    Serial.print("\r\nAdded: ");
    Serial.print(digitPins[i][j]);
    counter1++;
  }
}

Now, if you learn a little bit about how binary numbers work, and about
the binary operators in C and C++, you can rewrite your loop in a
simpler form:

for (int j = 3; j >= 0; j--) {
  int weight = 1 << j;      // 2 raised to the power j
  if (tempTime & weight) {  // if bit j of tempTime is set
    displayer[counter1++] = digitPins[i][j];
    Serial.print("Added bit ");
    Serial.print(j);
    Serial.print(", weight ");
    Serial.print(weight);
    Serial.print(", output ");
    Serial.println(digitPins[i][j]);
  }
}

As a side note, it is considered good practice to print a new line at
the end of each string you print (using println()), rather than at
the beginning.

Edit: As your display() function is way too complex for what it
does, I did not resist the temptation to simplify it:

void display() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
      digitalWrite(digitPins[i][j], time[i] & (1<<j));
}


Connecting multiple MAX30100/30102 via I2C I want to connect multiple (up to 4) MAX30100 or MAX30102 oximeter sensors to an Arduino via I2c. But I could not find a solution to change/assign the I2C address.

implementing-pulse-oximeter-using-max30100

datasheet MAX30100

LTC4316 is what you need. I haven't used it yet, but I know it from a project that did: mocap. It is an I2C translator IC.

Of course, if you need those ICs to be far away from each other, use a uC (or a separate Arduino) with all of those, and connect them with a different protocol!


Microcontrollers with built in HID support I am trying to build a wireless gamepad for which i am using NRF24l01 module for my wireless need and for Sending data to computer i need an mcu which support to act as hid device. So far, i got Attiny85 and mcu with atmega324u. But the problem is that attiny85 has very few pins and i cannot use it as for both hid and nrf module simutaneously due to pins defficiency. And atmega324u mcu are not avialable in my country. Can anybody suggest me some mcu with built in hid support.

The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).

The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.

You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like in this project


How to simulate delay() to debounce mechanical button using millis()? Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in.  However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.

Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:

int but = 12;
int led0 = 7;
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;

int ledCase = 0;
int butState = 0;
int oldButState = 0;

void setup()   {
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(but, INPUT_PULLUP);
}

void loop()    {

   oldButState = digitalRead(but);
   delay(10);
   butState = digitalRead(but);

   if (butState != oldButState && butState == LOW) {
     ledCase += 1;
     oldButState = butState;
   }

   if (ledCase > 4) {
    ledCase = 0;
   }

   Serial.println(ledCase);

switch (ledCase) {
case 0:
digitalWrite(led0, HIGH);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 1:
digitalWrite(led0, LOW);
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 2:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 3:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
break;
case 4:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
break;
}
}

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:

unsigned long onTime;
unsigned long delayTime;

void setup() {
delayTime = millis() + 10;
}

void loop()    {
oldButState = digitalRead(but);
onTime = millis();
if (onTime >= delayTime) {
butState = digitalRead(but);
delayTime = millis() + 10;
}
}

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

To better understand how you can do this it is good to understand first just what goes on when a button bounces.

It is, literally, bouncing - just like a ball when you drop it.  Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal.  It's either connected to ground, or it's not connected to ground.  And we're only really interested in when it's connected to ground.

More importantly we're interested in how long it's been connected to ground for.

By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground.  By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.

Take the following diagram for instance:

The blue line is the state of the button.  As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.

The red line is the difference between a timestamp that is set to be equal to millis() at the moment the button transitions from HIGH to LOW and the current millis() value, and is ignored when the button is HIGH.  As you can see the difference between that timestamp and the current millis() value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.

When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing.  Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.

To translate that into some code, you may end up with something like this (untested):

// Two variables to store remembered state information - the time
// of the last HIGH-LOW transition and the previous state of the
//  button.
static uint32_t debounceTime = 0;
static uint8_t buttonState = HIGH;

// Check to see if the button has changed state
if (digitalRead(buttonPin) != buttonState) {
    // Remember the new state
    buttonState = digitalRead(buttonPin);
    // If the new state is LOW ...
    if (buttonState == LOW) {
        // ... then record the time stamp
        debounceTime = millis();
    } else {
        // ... otherwise set the time stamp to 0 for "don't care".
        debounceTime = 0;
    }
}

// If the time stamp is more than 0 and the difference between now and
// then is greater than 10ms ...
if (debounceTime > 0 && (millis() - debounceTime > 10)) {
    // ... set the time stamp to 0 to say we have finished debouncing
    debounceTime = 0;
    // and do whatever it is you need to do.
    digitalWrite(ledPin, HIGH);
}

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the results of the debouncing that you react to, not the button state itself.


Sending char arry via nRF24L01 I am trying to send a char array using Arduino Uno board and nRF24L01 modules
Here is the code for both transmitter and receiver:
 #include <SPI.h> //~ #include <TMRh20nRF24L01.h> //~ #include <TMRh20RF24.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type //
 These are the IDs of each of the slaves const uint64_t slaveID[2] =
 {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

 RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

 char
> dataToSend[64]="e7665072be018b6b58ea9e40cf38553d6dc293cda4c9d94cda6e91ca61b3a073";

 unsigned long currentMillis; unsigned long prevMillis; unsigned long
> txIntervalMillis = 1000; int txVal = 0; float ackMessg[2]={1,2}; byte
 ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints
 that will be recieved

 void setup() {

    Serial.begin(9600);
     Serial.println("Track Control Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.enableAckPayload();
     radio.setRetries(3,5); // delay, count }

 //====================

 void loop() {

     currentMillis = millis();
     if (currentMillis - prevMillis >= txIntervalMillis) {

     radio.openWritingPipe(slaveID[0]); // calls the first slave
                                         // there could be a FOR loop to call several slaves in turn

     bool rslt;
     rslt = radio.write( dataToSend, sizeof(dataToSend) );
     Serial.print("\nRSLT (1 = success) ");
     Serial.println(rslt);
     Serial.print("Data Sent ");
     Serial.print(dataToSend[0]);
     Serial.print("  ");
     Serial.println(dataToSend[1]);
     if ( radio.isAckPayloadAvailable() ) {
         radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);

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

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type

 const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave

int valChange = 1;

 RF24 radio(CE_PIN, CSN_PIN);

 char  dataReceived[64];
 int ackData[2] = {12,23};

 void setup() {

     Serial.begin(9600);
     delay(1000);
     Serial.println("Hand Controller Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.openReadingPipe(1,deviceID);
     radio.enableAckPayload();
     radio.writeAckPayload(1, ackData, sizeof(ackData));
     radio.startListening();
 }

 void loop() {

     if ( radio.available() ) {
         radio.read( dataReceived, sizeof(dataReceived) );
          for (int x = 0; x <64; x++) {
       //if (dataReceived[x] < 16) {
       //  Serial.write('0');
     // }
       Serial.print(dataReceived[x]);}
       Serial.println();
         radio.writeAckPayload(1, ackData, sizeof(ackData));

         ackData[0] += valChange; // this just increments so you can see that new data is being sent
     }
}

And here is the output that I get

Hand Controller Starting
e7665072be018b6b58ea9e40cf38553d

TX code

#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID = 0xE8E8F0F0E1L  ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
int ackMessg[6];
byte ackMessgLen = 4;

uint8_t* hash;
uint8_t copy[32];
void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
      copy[i]=hash[i];
  }
  Serial.println();
}

void setup() {
  printf_begin();

  uint32_t a;
  unsigned long ms;

  Serial.begin(9600);

  radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.enableAckPayload();
    radio.setRetries(3,5); // delay, count

  // SHA tests
  Serial.println("Test: FIPS 180-2 B.1");
  Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  Serial.print("Result:");
  ms = micros();
  Sha256.init();
  Sha256.print("abc");
  printHash(Sha256.result());
  Serial.println();
  for(int x=0;x<32;x++)
        {   Serial.print(copy[x]);
            Serial.print(" ");
                                  }
            Serial.println();

  Serial.print(" Hash took : ");
  Serial.print((micros() - ms));
  Serial.println(" micros");
  Serial.println();

  }

void loop() {

  currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID);
    bool rslt,rsltt;
    rslt = radio.write( copy, 32 );

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }

}

Rx code

// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);
RF24 radioo(CE_PIN, CSN_PIN);
uint8_t  dataReceived[32];

int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.openReadingPipe(1,deviceID[1]);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();

}

void loop() {

 unsigned long startTimer = millis();

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        Serial.println();
        //Serial.println(startTimer);
        Serial.println();
        for(int x=0;x<32;x++)
        {Serial.print(dataReceived[x]);
        Serial.print(" ");}}
        ackData[0] += valChange; // this just increments so you can see that new data is being sent

    }

it is fully working now with both outputs on the same size


Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it? Ethernet shield problem. When running the WebServer example sketch, the Serial Monitor shows that server is at 0.0.0.0. Any suggestions how to debug it?

That's what it's supposed to be. It's called INADDR_ANY. Read an introductory text on networks and you'll understand what that means.

If you try to connect to the IP address you specified, you'll see that you can indeed connect.


Atmega328 component library for Protel 99 SE Any one know a component library for Arduino UNO (Atmega328, etc) for Protel 99 SE PCB design software?

All arduino design schematics are available from the Arduino website, e.g. for the Uno. However, these are in EAGLE format, I don't know if it's possible to convert.


Can I control LED brightness with potentiometer without any code, as well as reading the potentiometer value? I am just getting back into electronics and have started to play around with making my own button box.
I am trying to control an LED's brightness using a potentiometer, while also reading the potentiometer's value with the Arduino's analogue pin. I want to limit the number of pins I am using for things because I have lots of buttons that will need to be hooked up, so I am trying to control the LED without any code.
I have put together the following circuit (sorry, not my tidiest diagram. I am also using a Pro Micro rather than a Leonardo, but I didn't think that would make any difference :) ).

This works to a degree. I am able to adjust the LED brightness using the pot, and I do get a reading on the Arduino from the pot, however, the reading does not go up linearly as I would expect. It seems to get to about 500 out of 1023 at 4/5 of the rotation and then jumps up to 1023 within the last 1/5.
Could someone explain why this happens, and if it is even possible to do what I am attempting?
Thanks in advance!

You need to "buffer" the potentiometer to separate it from the LED and resistor. The simplest circuit for that is a unity-gain voltage follower with an op-amp:

simulate this circuit – Schematic created using CircuitLab
You want to choose a "Rail to Rail I/O" op-amp so that it can get right down to 0V and right up to 5V, otherwise you will clip the top and bottom of the range of the potentiometer.


Bluetooth connection and RX ,TX I have connected a RN-42 bluetooth (TX-D0, RX-D1, VCC-5V, GND_GND) to arduino.The problem is that when I run this code ,nothing happens it just upload to infinite or it doesn't. I am checking with tera term. Is there a problem with the connection of the pins? Also when I pair my android phone to the bluetooth it says paired on the phone but the blue light of the bluetooth doesn't switch on, like it's not connected.

  #include <SoftwareSerial.h>// import the serial library
   SoftwareSerial Genotronex(1, 0); // TX,RX
   int ledpin=13; // led on D13 will show blink on / off
   int BluetoothData; // the data given from Computer

  void setup() {
  // put your setup code here, to run once:
   Genotronex.begin(9600);
   Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
   pinMode(ledpin,OUTPUT);
  }

  void loop() {
    // put your main code here, to run repeatedly:
  if (Genotronex.available()){
     BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
  digitalWrite(ledpin,1);
  Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
   digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
   delay(100);// prepare for next data ...
 }

As commenter by RSM

The issue you are facing is because you are using pins 0 and 1

These are used by the arduino for uart.

So for starters please use any pin other that 0 and 1.  But if you insist that you do need to use these pins,  then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.


Connecting via serial with Arduino comand line Since inotool is dead, I'm trying to transition over to Arduino's built-in command line tool.

It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running ino serial would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.

How is this accomplished with the current Arduino command line tool?

If you are using linux, as I guess, you can look at this archwiki page. Even if is a wiki relative to archlinux OS some informations explained are LinuxOS independendent.

For your needs, you can use screen command. Here is an example: remember to substitute the serial port with the one wich arduino is connected (usually /dev/ttyACM* or /dev/ttyUSB*) and to specify the right baud rate.

screen /dev/ttyACM0 9600


Interfacing pc mouse (serial port DB-9) So I`ve got that mouse with serial connector. It is named serial so it should be easier to connect than even a ps2 mouse, right?

I can`t find any instruction on it. Or should I see instruction on ps2 mouse and plug in the same wires?
Btw mouse has only 4 wires connected inside, as usual PS2 mouse. I want to connect it the same way as ps2 mouse to get easy readings of rotary encoder.

UPD1: I`ve tried to connect it like a PS2 mouse according to this schema with no success. So either a mouse is dead or it uses some kind of different connection?

A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's RX/TX pins, you'll have to go through an RS-232 transceiver chip.

It also gets its power from the RTS line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!

Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
The X delta was encoded in the second byte;
The Y delta was encoded in the third byte.

  http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
The leading bit was still used to indicate start of packet;
The X, Y (and Z) wheels still indicated deltas.

  http://www.cpcwiki.eu/index.php/Serial_RS232_Mouse


Atmega328p with arduino without the board Perhaps this is a beginners question and I am not sure. I currently have a custom made circuit with an atmega328p chip connected to an mpu6050. However, when I program in Arduino I am not sure what to do? I can't pick a "board" as the atmega328p doesn't belong to a board? (from what I'm aware at least)
How in Arduino do I choose to program for my atmega328p chip? Without having to pick a board such as Arduino Uno etc. As I don't have any board for this. Or does the atmega328p chip always belong to a certain board?
I have a fully working circuit with a cyrstal (16MHz), battery sources, atmega328p etc. But I don't know how to program it with Arduino? I can program it in C, but would like to use Arduino due to certain libraries.

The board option is actually selecting a variant out of the installed cores (which provide the basic Arduino framework for a group of boards/chips). Each core can support multiple variants/boards/chips and can give each of them individual lists of options. There certainly also is a core, which supports the Atmega328p with all needed config options (like the frequency setting). You just need to install it from the boards manager.
Though, since you use a 16MHz crystal just like the Uno/Nano, you could just select the Uno or Nano as board. Neither the Arduino IDE, nor the Atmega328p can know, that the Atmega is actually a standalone one and not mounted on an Arduino board. So you can just use that board when you keep the config options inherent to an Arduino Uno/Nano (frequency setting and pin mapping mainly).


ATtiny85-DHT11-TM1637 I have tried many combinations and I can get the Attiny85 to display on the TM1637 just fine, but I cannot get ant readings from the DTH11, tried different pins, libraries. I upload code via UNO as isp and that works fine. Tried same code on UNO and it works.
This is my first question on here, I usually figure things, but also first ATtiny85 adventure.

#include <TM1637Display.h>
#include "DHT.h"
#define CLK 4
#define DIO 3
#define DHTPIN 2  //
#define DHTTYPE DHT11
int MTD (2000);
TM1637Display display = TM1637Display(CLK, DIO);
DHT dht(DHTPIN, DHTTYPE);

const uint8_t celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_D | SEG_E | SEG_F
}; // oC
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_E | SEG_F | SEG_G
}; // oF
const uint8_t Humidityh[] = {
  SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, SEG_C | SEG_D | SEG_E | SEG_F | SEG_B
}; // HU

void setup() {
  dht.begin();
  display.setBrightness(7);
}

void loop() {
  delay(1000);
  float Humidity = dht.readHumidity();
  float TemperatureC = dht.readTemperature();
  float TemperatureF = dht.readTemperature(true);

  display.showNumberDecEx(TemperatureF, 0b10000000, false, 2, 0);
  display.setSegments(Fahrenheit, 2, 2); delay(MTD);
  display.showNumberDecEx(Humidity, 0b10000000, false, 2, 0);
  display.setSegments(Humidityh, 2, 2); delay(MTD);
  display.showNumberDecEx(TemperatureC, 0b10000000, false, 2, 0);
  display.setSegments(celsius, 2, 2); delay(MTD-1000);
}

Found <TinyDHT.h> and all works ok, just what I wanted.


Smallest digital 3-axis gyroscope pcb for arduino? What is the smallest size digital 3-axis gyroscope pcb compatible with an arduino that I can buy or maybe make if its simple enough. I need one really really tiny probably around 0.8x0.1x0.5 (doesn't have to be that small but the smaller the better).

Thanks,

smallest board is no board.  pick a small BGA or LGA shaped accelerometer and superglue it face down to the arduino board then solder fine wires beween the chip terminals and arduino terminals.

search digikey for 'spi accelerometer'


Commucinate two arduino with each other I have 2 arduino Unos where each one works properly on its own.

I try to make them communicate with each other using serial communication (TX-RX ports).

When I try to upload my code to them I get this error :

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

what should i do to fix it ? (MY os is windows 10) thanks

Pins 0 and 1 on the Arduino Uno are used for serial communication with the computer over USB, including uploading sketches. If you connect anything to those pins you can interfere with the upload process.

To communicate between the two boards using serial communication without using pins 0 and 1 you can do software serial on other pins:
https://www.arduino.cc/en/Reference/SoftwareSerial


Arduino Human Infrared Sensor I started out again with Arduino (beginner), but I wanted to know if I could connect another human infrared sensor like this to the Arduino Uno. I know how to connect a simple pir like this one, but I dont know for sure how to connect the 12V one (if its possible). Guess the red wire goes to a seperate 12V power supply, brown goes to ground and blue then goes to a digital pin on the arduino arduino? I didnt really understand the description that was available for the 12V sensor, so thats why I am asking (I want to be entirely sure before buying).

Thanks

Blue - Ground, connect to Arduino GND
Brown - Power, connect to external 12V source.
Red - 12 V output. Connect via a diode to arduino input pin. Enable pullup on arduino pin.

This way when the sensor output is low it will pull the arduino pin low. When the output is high the diode blocks the 12V from frying the arduino while the internal pullup ensures the input pin goes to a safe voltage for a high pin.

Don't put the diode the wrong way around or things will go bang.

simulate this circuit – Schematic created using CircuitLab


Pass templated function as attachInterrupt parameter So I want to do something like this:

template<int PIN, int CHANNEL>
void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL>
void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL>
void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

but the compiler gives me this error

no matches converting function ‘rising’ to type ‘void (*)()’

Can I even do this, or do I have to write all the functions by myself?

Try this:

template<int PIN, int CHANNEL> void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL> void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL> void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

The problem is actually the Arduino preprocessor. It adds illegal forward declarations if template functions are formated as your original code.


Sparkfun CCS811 Air Quality Sensor is just not workin i have an Arduino uno board and a sparkfun ccs811 sensor. I tried to reproduce the howto from the sparkfun homepage (https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?_ga=2.45231532.967238096.1560976781-258902726.1560976781), including the error states part.

I uploaded one picture of the wiring (updated). I also tried to use an alternative hardware connection with SDA to A4 and SCL to A5 as it is mentionned in the code comments (see homepage).

However, it is just not working and i always get this error code in the serial monitor beginCore exited with: I2C_ERROR

Here is my code (without the top comment block):

#include <Wire.h>

#include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
Serial.begin(9600);
Serial.println("CCS811 Basic Example");

Wire.begin(); //Inialize I2C Harware

//It is recommended to check return status on .begin(), but it is not
//required.
CCS811Core::status returnCode = mySensor.begin();
Serial.print("beginCore exited with: ");
switch ( returnCode )
{
case CCS811Core::SENSOR_SUCCESS:
 Serial.println("SUCCESS");
 break;
case CCS811Core::SENSOR_ID_ERROR:
 Serial.println("ID_ERROR");
 break;
case CCS811Core::SENSOR_I2C_ERROR:
 Serial.println("I2C_ERROR");
 break;
case CCS811Core::SENSOR_INTERNAL_ERROR:
 Serial.println("INTERNAL_ERROR");
 break;
case CCS811Core::SENSOR_GENERIC_ERROR:
 Serial.println("GENERIC_ERROR");
 break;
default:[enter image description here][2]
 Serial.println("Unspecified error.");
}

if (returnCode != CCS811Core::SENSOR_SUCCESS)
{
Serial.println(".begin() returned with an error.");
while (1); //Hang if there was a problem.
}
}

void loop()
{
//Check to see if data is ready with .dataAvailable()
if (mySensor.dataAvailable())
{
//If so, have the sensor read and calculate the results.
//Get them later
mySensor.readAlgorithmResults();

Serial.print("CO2[");
//Returns calculated CO2 reading
Serial.print(mySensor.getCO2());
Serial.print("] tVOC[");
//Returns calculated TVOC reading
Serial.print(mySensor.getTVOC());
Serial.print("] millis[");
//Simply the time since program start
Serial.print(millis());
Serial.print("]");
Serial.println();
}

delay(10); //Don't spam the I2C bus
}

You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.


ttyACM0 no such file or directory On Ubunutu 14.04 I have an Arduino Uno which communicated with the computer (Ubunutu 14.04) fine till 6 days ago (I assume some software update is to blame).

Now when trying to upload I get

processing.app.SerialNotFoundException: Serial port '/dev/ttyACM0' not found. Did you select the right one from the Tools > Serial Port menu?   at processing.app.Serial.(Serial.java:191)    at processing.app.Serial.(Serial.java:77)     at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)    at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:175)   at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)     at processing.app.Sketch.upload(Sketch.java:1671)   at processing.app.Sketch.exportApplet(Sketch.java:1627)     at processing.app.Sketch.exportApplet(Sketch.java:1599)     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)     at java.lang.Thread.run(Thread.java:745)

When I sudo ls /dev/ttyA*

I get

ls: cannot access /dev/ttyA*: No such file or directory

So it does not look like a permission issue.

when I lsusb

I get

Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 003: ID 04f2:b39a Chicony Electronics Co., Ltd
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

So it does not even see the device (which is connected and pulling current).

when I dmesg before and after connecting the Arduino, I don't see anything new.

I tried switching USB cables, and switching USB ports on the machine (both ports work with a mouse), but in vain.

What went wrong and how do I fix it ?

Thanks,
David.

Ok, it sounds like there is an issue with the ATMega(8/16)U2 chip or its surroundings.  It might just need its firmware refreshing (which can be done with another Arduino as a programmer) or it might be plain dead.

Another possibility is the USB socket itself.  I have two UNOs, one which is perfectly fine, and one where I need to hold the cable at just the right angle for it to connect properly.  You can try using a fine needle to try and raise the four metal strips in the USB connector a fraction to make better contact.


Built-in LED turns on when I touch the input port I'm a beginner. I bought a new Arduino and I uploaded the basic example button code.

const int buttonPin = 2;
const int ledPin =  13;
int buttonState = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

But the problem is that when I touch port 2 the output is getting so I changed the port number 2 to 3 even though without any supply the output is getting on.

Give me some suggestion.

When you are reading digital data through a pin you must make sure that you are steering that input pin to a stable state when no input is present.
You can do this by using either a pullup or a pulldown resistor which you can connect externally or you can use the in built pullup.
You can use a 10k ohm resistor to pulldown by connecting it to the button end where your digital pin is connected and the other to ground.
By doing this your above code must work fine.
I think by touching the pin you are actually pulling the voltage state down.
Hope this helps


Arduino + CO2 + humidity + noise + temperature sensors on one board I'm looking for an Arduino board that include this sensors out of the box:

CO2
Humidity
Noise
Temperature

I've found here Using the Waspmote Sensor Board something that could be enough, but I'm searching for more options.

I did a lot of searches on the Internet without good results.

Any suggestions?

For humidity and temperature you can plug the DHT11 or DHT22 to your arduino. DHT11 is cheaper but you'll get a more precise value with DHT22.

For noise you have ready made PCB like these : here
You'll only have to plug it to GND, 5V and analog input.

For CO2 this is more complicate. There is a cheap but very unprecise option, using a MQ135 sensor, here is a tutorial: here
Otherwise there are better sensors like the K30 but they are much more expensive.


ESP8266-01S Stopped responding after second launch Here's the code:

#include <SoftwareSerial.h>
#define RX 6
#define TX 5

String AP = "...";
String PASS = "...";

SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(9600);
  Serial.println("Setup started");

  esp8266.begin(115200); // Change this to the factory baudrate used by ESP8266
  delay(1000);

  Serial.println("Setting BAUDRATE to 9600");
  esp8266.println("AT+IPR=9600");
  esp8266.begin(9600);
  delay(500);
  Serial.println("Setup finished");

  reset();
  connectWifi();
}

//reset the esp8266 module
void reset() {
  Serial.println("Resetting...");
  esp8266.println("AT+RST");
  delay(3000);

  if (esp8266.find("OK"))
    Serial.println("Module Reset");
  else
    Serial.println("Module Reset Failed!!!");
}

//connect to your wifi network
void connectWifi() {
  Serial.println("Connecting to Wifi...");
  String cmd = String("AT+CWJAP=\"") + AP + "\",\"" + PASS + "\"";
  esp8266.println(cmd);
  delay(4000);
  Serial.println("Checking Wifi...");
  int ctr=0;
  while(!(esp8266.find("OK"))) {
    if(esp8266.find("ERROR")) {
      Serial.println("Cannot connect to wifi...");
      break;
    }
    delay(50);
    ++ctr;
    if(ctr>10){
      Serial.println("Cannot connect to wifi...");
      break;
    }
  }
  Serial.println("ConnectWifi finished");
}

The ESP8266-01S wires are as follows:

GND to arduino ground
3v3 to arduino 3v3
RX to arduino pin 5
TX to arduino pin 6
EN to arduino 3v3

The thing worked for one time, and when I re-compiled and sent it again without any changes or even button presses, it stopped working. Furthermore, if I connect ESP module directly through arduino rx and tx and connect arduino reset to ground, I still don't get anything. The led on the esp is blinking during data transfers, but everything else doesn't change and I get no response at all.

You need to re-flash your AI Thinker firmware. AT+IPR kills certain versions of the firmware.

Install the latest version of the firmware and use AT+UART_DEF=9600,8,1,0,0 and AT+UART=9600,8,1,0,0. (The former sets the default baud rate, the latter the current baud rate).

You can read more here.


Get csv field values I am uploading data using Thingspeak and I would like to get only values stored in a field. Is there any way to get this in a cvs http request?

When you call a cvs http url, you get:

What I am trying to get is just the value in field2: 10,10,12,12,16 without the headers.

You can use this format to achieve what you described:

http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)

Source: http://community.thingspeak.com/documentation/api/

Edit: It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:

  int i;
  String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";

  for (i = response.length()-1; i >= 0 ; i--)
  {
    if (s.charAt(i) == ',') break;
  }
  String value = response.substring(i+1);
  Serial.println(value); // This will show only 5