text:
error: expected primary-expression before '(' token
I have a decent level of programming skill, or at least I thought so. I've been getting an error when compiling this Ardulno sketch. I don't really know what this error means or how to fix it. What's wrong with my code that's causing these errors. I was in the middle of making a big change to my code, so a lot of it is commented out because I haven't gotten to those parts.
code:
#include <LinkedList.h>

const uint8_t PinLeft = 2;
const uint8_t PinMiddle = 3;
const uint8_t PinRight = 4;
const uint8_t PinLED = 13;

enum MouseButtons {LEFT, MIDDLE, RIGHT} ;

bool leftPressed = false;
bool middlePressed = false;
bool rightPressed = false;

void sendMouseState() {
    if (leftPressed == true && middlePressed == false && rightPressed == false) {
        Mouse.set_buttons(1, 0, 0);
    } else if (leftPressed == true && middlePressed == true && rightPressed == false) {
        Mouse.set_buttons(1, 1, 0);
    } else if (leftPressed == true && middlePressed == true && rightPressed == true) {
        Mouse.set_buttons(1, 1, 1);
    } else if (leftPressed == true && middlePressed == false && rightPressed == true) {
        Mouse.set_buttons(1, 0, 1);
    } else if (leftPressed == false && middlePressed == true && rightPressed == false) {
        Mouse.set_buttons(0, 1, 0);
    } else if (leftPressed == false && middlePressed == false && rightPressed == true) {
        Mouse.set_buttons(0, 0, 1);
    } else if (leftPressed == false && middlePressed == true && rightPressed == true) {
        Mouse.set_buttons(0, 1, 1);
    } else if (leftPressed == false && middlePressed == false && rightPressed == false) {
        Mouse.set_buttons(0, 0, 0);
    }
}

void mouseButtonPress(MouseButtons theButton);
void mouseButtonPress(MouseButtons theButton) {
    if (theButton == MouseButtons::LEFT) {
        leftPressed = true;
    } else if(theButton == MouseButtons::MIDDLE) {
        middlePressed = true;
    } else if (theButton == MouseButtons::RIGHT) {
        rightPressed = true;
    }
}

void mouseButtonRelease(MouseButtons button);
void mouseButtonRelease(MouseButtons button) {
    if (button == LEFT) {
        leftPressed = false;
    } else if(button == MIDDLE) {
        middlePressed = false;
    } else if (button == RIGHT) {
        rightPressed = false;
    }
}

volatile unsigned int nextPressLeft = 0;
volatile unsigned int nextPressCenter = 0;
volatile unsigned int nextPressRight = 0;
const int timeBetween = 150; //milliseconds

enum ActionType {KB, MOU}; //keyboard or mouse

class Action {
    public:
        uint16_t keyCode;
        ActionType actionType;

        Action (uint16_t keyCode, ActionType actionType) {
            this->keyCode = keyCode;
            this->actionType = actionType;
        }

};

class ModeAction {

    public:
        LinkedList<Action> *keys = new LinkedList<Action>();

        void addAction(Action action) {
            keys->add(action);
        }

};

class ActionManager {

    private:
        uint8_t modeL = 1;
        uint8_t modeM = 1;
        uint8_t modeR = 1;

        LinkedList<ModeAction> *lActions = new LinkedList<ModeAction>();
        LinkedList<ModeAction> *mActions=new LinkedList<ModeAction>();
        LinkedList<ModeAction> *rActions=new LinkedList<ModeAction>();

        bool lActing = false, mActing = false, rActing = false;

    public:
        ActionManager() {
            //actions for left switch
            //mode 1
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(MouseButtons.LEFT, ActionType.MOU));
            //mode 2
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_F11, ActionType.KB));
            //mode 3
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_LEFT_CTRL, ActionType.KB));
            lActions->get(lActions->size() - 1).addAction(Action(KEY_LEFT_ALT, ActionType.KB));
            //mode 4
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_W, ActionType.KB));

            //actions for middle switch
            //mode 1
            mActions->add(ModeAction());
            mActions->get(lActions->size() - 1).addAction(Action(MouseButtons.MIDDLE, ActionType.MOU));

            //actions for right switch
            //mode 1
            rActions->add(ModeAction());
            rActions->get(lActions->size() - 1).addAction(Action(MouseButtons.RIGHT, ActionType.MOU));

        }

        void cycleModeL() {
            this->modeL++;
            if(this->modeL >= lActions->size()) {
                this->modeL = 1;
            }
        }

        void cycleModeM() {
            this->modeM++;
            if(this->modeM >= mActions->size()) {
                this->modeM = 1;
            }
        }

        void cycleModeR() {
            this->modeR++;
            if(this->modeR >= rActions->size()) {
                this->modeR = 1;
            }
        }

    private:

        //void doDownActions(ModeAction modeActions, uint8_t mode) {
            //for (int i = 0; i < modeActions.at(mode).keys.length(); i++) {
                //if (modeActions[mode][i].keys[i].actionType == ActionType.KB) {
                    //Keyboard.press(modeActions[mode].keys[i].keyCode)
                //} else if (modeActions[mode].keys[i].actionType == ActionType.MOU) {
                    //mouseButtonPress(modeActions[mode].keys[i].keyCode);
                //}
            //}
            //sendMouseState();
        //}
//
        //void doUpActions(ModeAction modeActions, uint8_t mode) {
            //for (int i = 0; i < modeActions[mode].keys.length(); i++) {
                //if (modeActions[mode][i].keys[i].actionType == ActionType.KB) {
                    //Keyboard.release(modeActions[mode].keys[i].keyCode)
                //} else if (modeActions[mode].keys[i].actionType == ActionType.MOU) {
                    //mouseButtonRelease(modeActions[mode].keys[i].keyCode);
                //}
            //}
            //sendMouseState();
        //}

    public:

        //void leftDown() {
            //if (lActing == false) {
                //lActing = true;
                //doDownActions(lActions, modeL);
            //}
        //}
//
        //void middleDown() {
            //if (mActing == false) {
                //mActing = true;
                //doDownActions(mActions, modeM);
            //}
        //}
//
        //void rightDown() {
            //if (rActing == false) {
                //rActing = true;
                //doDownActions(rActions, modeR);
            //}
        //}
//
        //void leftUp() {
            //if (lActing == true) {
                //lActing = false;
                //doUpActions(lActions, modeL);
            //}
        //}
//
        //void middleUp() {
            //if (mActing == true) {
                //mActing = false;
                //doUpActions(mActions, modeM);
            //}
        //}
//
        //void rightUp() {
            //if (rActing == true) {
                //rActing = false;
                //doUpActions(rActions, modeR);
            //}
        //}

};

ActionManager actionManager = ActionManager();

void setup() {

    Serial.begin(115200);

    pinMode(PinLED, OUTPUT);

    //pinMode(PinRight, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinRight, isrChangeR, CHANGE); // interrrupt is data ready
//
    //pinMode(PinMiddle, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinMiddle, isrChangeM, CHANGE); // interrrupt is data ready
//
    //pinMode(PinLeft, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinLeft, isrChangeL, CHANGE); // interrrupt is data ready

}

void loop() {

    //if (Serial.available()) {
////change mode
        //mode = Serial.parseInt();
//
////release all buttons
        //Keyboard.releaseAll();
        //Mouse.set_buttons(0, 0, 0);
//
////turn off LED
        //digitalWrite(PinLED, LOW);
//
////flush the serial input buffer
        //while (Serial.available()) {
            //Serial.read();
        //}
//
    //}
    //delay(1000);
    //Serial.println("Running");
}

//void isrChangeL() {
    //cli();
    //if (digitalRead(PinLeft) == LOW && nextPressLeft < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); //set the LED on
//
        //if (mode == 0) {
            //Mouse.set_buttons(1, 0, 0);
        //} else if (mode == 1) {
            //Keyboard.press(KEY_F11);
        //} else if (mode == 2) {
            //Keyboard.press(KEY_LEFT_CTRL);
            //Keyboard.press(KEY_LEFT_ALT);
        //} else if (mode == 3) {
            //Keyboard.press(KEY_W);
        //}
//
        //nextPressLeft = millis() + timeBetween;
//
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
//
        //if (mode == 0) {
            //Mouse.set_buttons(0, 0, 0);
        //} else if (mode == 1) {
            //Keyboard.release(KEY_F11);
        //} else if (mode == 2) {
            //Keyboard.release(KEY_LEFT_CTRL);
            //Keyboard.release(KEY_LEFT_ALT);
        //} else if (mode == 3) {
            //Keyboard.release(KEY_W);
        //}
//
        //nextPressLeft = millis() + timeBetween * 0.6;
//
//
    //}
    //sei();
//}
//
//void isrChangeM() {
    //cli();
////if (digitalRead(PinMiddle) == LOW && nextPressCenter < millis())
////{
////Keyboard.press(KEY_SPACE);
////delay(250);
////Keyboard.release(KEY_SPACE);
////}
//
    //if (digitalRead(PinMiddle) == LOW && nextPressCenter < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); //set the LED on
////Mouse.set_buttons(0, 1, 0);
//
        //nextPressCenter = millis() + timeBetween;
//
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
////Mouse.set_buttons(0, 0, 0);
//
        //nextPressCenter = millis() + timeBetween * 0.6;
//
//
    //}
//
    //sei();
//}
//
//void isrChangeR() {
    //cli();
    //if (digitalRead(PinRight) == LOW && nextPressRight < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); // set the LED on
        //Mouse.set_buttons(0, 0, 1);
////Keyboard.press(KEY_F11);
        //nextPressRight = millis() + timeBetween;
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
        //Mouse.set_buttons(0, 0, 0);
////Keyboard.release(KEY_F11);
        //nextPressRight = millis() + timeBetween * 0.6;
    //}
    //sei();
//}

compiler log:
Compiling debug version of 'click_switch_5_cycling' for 'Teensy LC'
click_switch_5_cycling.ino: In constructor ActionManager::ActionManager()

click_switch_5_cycling.ino: 106:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 106:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 106:83: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 109:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 109:73: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 112:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 112:79: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 113:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 113:78: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 116:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 116:71: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 121:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 121:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 121:85: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 126:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 126:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 126:84: error: expected primary-expression before '.' token

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of bool LinkedList<T>::add(T) [with T = Action]
click_switch_5_cycling.ino:83: required from here

LinkedList.h: 192:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h:19: note  ListNode<Action>  ListNode() is implicitly deleted because the default definition would be ill-formed
struct ListNode

LinkedList.h: 19:8: error: no matching function for call to 'Action::Action()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of ListNode<T>* LinkedList<T>::getNode(int) [with T = ModeAction]
LinkedList.h:314: required from T LinkedList<T>  get(int) [with T = ModeAction]
click_switch_5_cycling.ino:106: required from here
LinkedList.h: 160:9: warning: converting 'false' to pointer type 'ListNode<ModeAction>*' [-Wconversion-null]
return false
LinkedList.h: In instantiation of bool LinkedList<T>::add(int, T) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 177:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h: In instantiation of bool LinkedList<T>::unshift(T) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 218:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h: In instantiation of T LinkedList<T>::remove(int) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 290:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
Error compiling project sources
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
Debug build failed for project 'click_switch_5_cycling'

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::pop() [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 242:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::shift() [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 268:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::get(int) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 316:14: error: no matching function for call to 'Action::Action()
T())
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

Thanks for any help you can give me about what these errors are and how to fix them.

You seem to have been programming in Java recently, because many of your errors have a Java ‘whiff’ to them. This, as you’ve tagged, is C++, not Java.

sendMouseState:
a. You wrote leftPressed == true. This is much more simply expressed by the expression leftPressed.
b. You wrote middlePressed == false. This is much more simply expressed using the “not” operator !, as in !middlePressed.
c. The code tests all eight possible combinations of leftPressed, middlePressed and rightPressed, calling Mouse.set_buttons(#,#,#);
However, bools evaluate to numbers: false evaluates to 0, while true evaluates to 1. All eight tests, and therefore the entire function, can therefore be boiled down to the single line:
Mouse.set_buttons(leftPressed, middlePressed, rightPressed);
You declared to the compiler, in a few places, “There’s going to be a function called (e.g) void mouseButtonPress(MouseButtons theButton);”
That’s fair enough - but the compiler only needs that if you’re going to call the function before you define it. Since you follow the declarations immediately by the definitions, the declarations are unnecessary: get rid of them.
Use of enums:
Declaring an enum lets you use symbols instead of raw numbers: well done! However, that’s all you need to use: the enum’s symbol: LEFT, MIDDLE or RIGHT is all you need.
If you do feel the need to express the enum’s name, you need to use the :: operator, not the . operator: MouseButtons::LEFT.
Use of new:
You do not need to call new to create members of classes. Well, OK, you might if they’re declared as pointers (which you have done), but that’s your problem: you should declare them as simple members, not pointer members.
For example, instead of:
LinkedList<Action> *keys = new LinkedList<Action>();

you simply need:
LinkedList<Action> keys;

Note that no new is needed now. Then, everywhere that you dereference the member with keys->add(action);, you use keys.add(action); instead.
Use of this->:
You use this-> a lot. You practically never have to: however, the one time you did need to was in the code:
Action (uint16_t keyCode, ActionType actionType) {
    this->keyCode = keyCode;
    this->actionType = actionType;
}

Here, this-> was needed to distinguish the class members from the passed-in parameters that have the same name. However, if you’d written the constructor correctly, using initialisation instead of assignment, you wouldn’t have needed this-> here either:
Action (uint16_t keyCode, ActionType actionType) :
    keyCode(keyCode),
    actionType(actionType) {
}

add() followed by get():
You use the following code:
lActions.add(ModeAction());
lActions.get(lActions->size() - 1).addAction(Action(LEFT,MOU));

That is, you add an empty ModeAction, then fetch it back with get(...) before manipulating it. Don’t.
Instead, create a temporary ModeAction object, get it ready, then add() it to the list:
ModeAction lMode1;
lMode1.addAction(Action(LEFT,MOU));
lActions.add(lMode1);

1a and 1b are bad practice in Java too, 1c and 6 are bad algorithm (n Java too)

Dart, actually - been trying to learn it. Thanks for your detailed response.

a,b. I'm working with other people who aren't really programmers so I wanted to keep it explicit.
c. That's a good point, thanks.
I did that because I was getting the error: "variable or field 'mouseButtonPress' declared void" and I read that that was how to fix it. Something about the way Arduino handles function definitions.
I want the code to be explicit, so I'll change those to :: .

I was using example code given by the LinkedList library (https://github.com/ivanseidel/LinkedList).
Ok.
Ok, I changed those.

I think I made all the changes you suggested, but it still won't compile. Here's the new code https://gist.github.com/dude8604/98f7d8e7e6f4d74349b1b974e8ea0d17 and compiler log https://gist.github.com/dude8604/e9685c4b49b6c90922ad09a69b5e4c34
It seems like most of the errors point to the LinkedList library. Are the remaining errors with the library or my code? Thanks.

@dude8604 4. That example LinkedList code is... abbreviated. It starts simply enough with a normal variable, then talks about creating one with new. It wasn't implying that was how it had to be done... It's also got a bug in it: I'll send a Pull request to the author. Edit: No need - it's already there, just not actioned. Sigh!

@dude8604  Since you want to create a linked list of Actions, in your Action class you need to have a "default" constructor: one which takes zero parameters. If you add the line
"Action () : keyCode(0), actionType(KB) {}"
to the class, LinkedList<Action> will now compile.

The compiler is giving you a clue that the problem is around line 106. You have there:
  LinkedList<ModeAction> *lActions = new LinkedList<ModeAction>();
  LinkedList<ModeAction> *mActions=new LinkedList<ModeAction>();
  LinkedList<ModeAction> *rActions=new LinkedList<ModeAction>();

You can't do procedural code (like new) in a data declaration. Also, I doubt that there is a function to be called so I would get rid of the brackets. Initializing member fields should be done in the constructor, not in the declaration.

I moved the assignment part into the constructor but I'm still getting similar errors. Should I edit my code and compiler log in the original post?

should not be a problem with C++11 https://en.cppreference.com/w/cpp/language/data_members

This isn't a forum, so to-ing and fro-ing with changes to the original post makes the question a moving target, and then the answers look meaningless. Hopefully John Burger's rather comprehensive answer will help you without you having to do that.

Juraj is right however that declaring pointers like that is OK under C++11. However as John Burger points out, it is easier not to use pointers in the first place. For one thing, if you are going to use new then you should use delete in the destructor.

you use wrong syntax to access an enum member. use :: not .
Action(MouseButtons::LEFT, ActionType::MOU)
EDIT:
second error is that LinkedList requires constructor without parameters on the template type
add constructor without parameters to class Action

Re: second error, Is there another Arduino vector library that wouldn't require that?

I tried it and now the program freezes.

why do you want to use dynamic vector? use array


text:
How can I stock data, and send them over by serial?
I want to make an array with data from the sensor. In data, I have displacement in x/y axis. I want to send them in the array, because in my python code I don't send them one by one, slow down really quickly program.
Arduino code responsible for sensor
class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    Serial.print(mi ->dX, DEC);
    Serial.print(",");
    Serial.println(mi ->dY, DEC);

};

I tried to do something on my own, but I get stuck with an error about data not in the scope. I try some variant placing it, but I don't succeed .
class MouseRptParser : public MouseReportParser {

 void OnMouseMove (MOUSEINFO *mi); };

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{ int i;   for (i=0;i<10;i+2)   {
        data[i]=(mi ->dX, DEC);
        data[i+1]=(mi ->dY, DEC);   }
  Serial.println(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9]);

    delay(20); };

EDIT:  I have now program that's making an array of 10 cells, but values in it are constatnt 10.
#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
int data[10];

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    for (int i=0; i<10; i=i+2)
  {
    data[i]=(mi->dX, DEC);
    data[i+1]=(mi->dY, DEC);

  }
  for(int j=0; j<10; j=j+1)
  {
  Serial.print(data[j]);
  Serial.print(",");
}
Serial.println();
  delay(100);
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
    Serial.begin( 9600 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    //Serial.println("Start");

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

    HidMouse.SetReportParser(0, &Prs);
}

void loop()
{

  Usb.Task();

}

There is no such thing as "all at once" with serial. The whole point of serial is that it sends things one character at a time.
It is entirely up to you to decide what constitutes one "block" of data.
There is absolutely no difference (besides some slight processing overheads) between:
Serial.print("Hello");
Serial.print(" ");
Serial.println("World");

and:
Serial.println("Hello World");

Both of them result in Serial sending:
H
e
l
l
o
[space]
W
o
r
l
d
[cr]
[lf]

No matter how you "batch" stuff together (or attempt to) it makes no difference.
You need to have:

Some way of identifying the start of a block of data,
A mechanism to receive the entire block a byte at a time, and
Some way of identifying the end of a block of data.

How you do that is entirely up to you.

Here's an example of how to arrange the storage:
class MouseRptParser : public MouseReportParser
{
    private:
        int dx[10];
        int dy[10];
        int dpos = 0;

    protected:
        void OnMouseMove (MOUSEINFO *mi) {
            dx[dpos] = mi->dX;
            dy[dpos] = mi->dY;
            dpos++;

            if (dpos == 10) {
                dpos = 0;
                for (int i = 0; i < 10; i++) {
                    Serial.print("X");
                    Serial.print(dx[i]);
                    Serial.print("Y");
                    Serial.print(dy[i]);
                }
                Serial.println();
            }
        }
};

What that gives you is a pair of 10-entry arrays, one for X and one for Y values. Each time a report arrives the current DX and DY values are stored. The pointer for where to store is incremented.  Then, if that pointer equals 10, reset it to 0 and print all the values.
I chose a format that gives you:
X3Y-2X2Y-4X6Y8X-3Y7X6Y38X176Y76X-4Y8X8Y3X39Y-32X71Y4

That is, an "X" followed by a decimal value for a change in X, and a Y followed by a decimal value for a change in Y. The whole lot is then terminated by a standard CR/LF line ending pair.

OK. I get it. I just need a a way to storage data, and send them over. I have now code to make an array of 10 elements and send them in loop, but its sending constant value. Check my edit post.

@Trzywu I don't think you are clear in your own mind exactly what you are trying to achieve. At the moment you take the X/Y coordinates and save them 5 times each in an array: x,y,x,y,x,y,x,y,x,y. Then you print those. What do you actually want to do? What data do you want to save? When do you want to send that data to the PC?

I want to send data in format like this x1,y1,x2,y2  and so on to x5,yy or x10,y10.  I want them send in some delay, i will figure out exact number when i get this portion of data.

So you want to store 5 coordinate pairs, and only when you have gathered 5 pairs do you want to send them to the PC. So you need to have some concept of how many pairs you have received, and only store the current pair in the current slots of the array. Only when the array is full do you do anything with Serial.

Please, can you be more specific?  I am reserving storage in this line"int data[10];" and  saving for respective cell here  " for (int i=0; i<10; i=i+2)
{
data[i]=(mi->dX, DEC);
data[i+1]=(mi->dY, DEC);
}"
Or am i missing something?

You are saving in every cell from 0 to 10. You do not want a for loop there. You just want some variable to say where in the array you currently are, and increment it only once for each report you receive. Only when the array is full (current == max) do you print the contents and reset the "current" pointer to the start of the array.

@Trzywu I have added an example to my answer.

Thank you, i was sleeping over.  I change some code to have specified character to split in.  Once again thank you very much.

source: Stack Exchange

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

sort: votes


text:
Minimum separation of MOSFET
I have three MOSFET in a row, each separated about 2.5mm apart with the backs facing each other. Is this a good idea?
N.B
Each MOSFET will be sinking 20mA and 60 mA in total for all three MOSFET. I am using an IRF540. The schematic below is for ONE MOSFET.

yes it's fine. worse-case, one switches the other on if they get bent.

Arduino's are often used to drive MOSFETs to sink current for higher loads, so this seems perfectly on topic to me.  I even made a board with 4 shift registers and 32 1A MOSFETs http://www.crossroadsfencing.com/BobuinoRev17/ for driving LED strips and small motors from an Arduino.

@CrossRoads Arduino was created in Ivrea, Italy. Does this mean that on arduino.stackexchange travelling questions to Italy are on topic?

Power dissipation is only a couple of milli-watts. So heat is not an issue.
Just make sure the metal tabs can’t touch each other. Personally I might add some Kapton tape. Electrical tape would work in this case, but feel wrong to me.

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


text:
How to use RTC memory in NodeMCU to count awakes from deep sleep?
Problem: I need to retry at least 3 times (before giving up) to reconnect my NodeMCU if it doesn't get connected to Wifi, through deep sleep cycles in order to save batteries. I thought to use RTC memory to save a counter, but it doesn't work because content of RTC RAM is unpredicatble at first power up.
Following is a NOT WORKING code, but it gives the idea of what I need to achieve. The problem is: the kounter variable is persistent through cycles, but its very first value is unpredicatble.
#define DONEPIN 5
uint32_t kounter;

void setup() {
    digitalWrite(DONEPIN, HIGH);
    //WiFi setup functions...
    // .....
    if (WiFi.status() != WL_CONNECTED) {
        ESP.rtcUserMemoryRead(0, &kounter, sizeof(kounter));
        kounter++
        if (kounter > 3) {
            digitalWrite(DONEPIN, LOW);
        }
        ESP.rtcUserMemoryWrite(0, &kounter, sizeof(kounter));
        ESP.deepSleep(60e6);
    }
}

@Majenko interesting! Didn’t know that. I removed my comment.

@Gerben So did I :P

You can differentiate between first powerup and resets (after deep sleeps) by using rtc_get_reset_reason(0). If I’m not mistaken this should return a 1 on powerup. So when this returns 1 overwrite the RTC memory with zero. Otherwise read the memory.

The simplest trick is to use more than one memory location. Have one, as you have now, as a counter, and then have one or more as a "This has been configured" flag.
Ideally you want the flag to have a very low probability of occurring randomly, so using a combination of a number of memory locations would improve that.
For instance, if you read memory locations 1-4 and look for four specific bytes, that gives you about a 1 in 4 billion possibility of it happening randomly.
If you don't see those four bytes, you set the counter byte to 0 (or whatever you want your initial value to be) and set the other 4 memory locations to contain your 4 flag bytes.
Using 8 bytes for your flag would give you in the order of 1 in 1.8x1019 chance of it occuring randomly.
These "flag byte combination" are often called "magic numbers" and are used all over the place to identify either what something is, or if something is valid.

So, can I use a struct { byte counter; byte validation[7]} ?

Sure, you could do. I don't know what the functions allow you to easily pass though, so it may be simpler to just directly access the memory's bytes.

I realize this is really old, but it is still the top of the list when you search for RTCmem read/write. While it isn't maybe as "by the book" as the 'correct' answer above, there is a really simple way to deal with the "the rtcmem value is something ridiculous on first read" issue. When you first power on the esp8266 or after a button-based reset, the rtcmem value WILL be something insane. You can account for it in the code by ignoring anything that is outside the count you want. Since my application "sleeps" for 4 hours, which in esp8266 means 4, 1 hour loops, I simply say if the rtcMem value is outside that range, it is obviously bogus, set it to what I want, and go about your business:
void writeToRTCMemory() {
  if (rtcMem.count == MAXHOUR) {
    rtcMem.count = 1;
  } else {
    if (rtcMem.count < 1) {
      rtcMem.count = 1;
    }
    if (rtcMem.count > 4) {
      rtcMem.count = 1;
    }
    rtcMem.count++;
  }

As long as your device has not lost power, or you have not pushed the reset button, this will keep it looping the way you want for as long as it has enough juice to deep sleep. (My solar powered sensors with this loop last around 2/2.5 weeks in the mid winter and much longer in summer)


text:
Connect arduino pro mini 3.3v to 5v
Is it safe to run an arduino pro mini 3.3v by 5v?
I mean directly connect 5v to vcc not raw pin.

Have you examined the schematic yet?

Can you remove the voltage regulator? Just to be sure that it doesn't get reverse voltage.

Yes you can.
The only difference between the 3.3 V and 5 V Pro Mini is the crystal and the voltage regulator.

Yes, an 8 MHz resonator-clocked Promini will happily work at 5V vs 3.3V.
If you want, add a diode from VCC to the RAW pin to protect the regulator, altho it's datasheet does not indicate such is warranted.  Anecdotally, I used about 10 of these in my fencing club powered from 5V to the VCC line for quite a few years with no such protection and they ran fine for ~ 10 years, until we closed the club.


text:
Use an Arduino Mega in a incubator (high humidity)
I wonder whether it is possible to use an Arduino Mega in a cell incubator.
In the incubator there is a temperature of 37°C, 5% CO2 in the atmosphere and a high relative humidity of around 95% - 98%. I think the temperature (specs of ATmega2560, temperature range: -40 °C to 85 °C) and the CO2 is no problem.
But I am concerned the condensation due to the high humidity will cause damage.
One mitigation could be, that I first pre-warm the Arduino Mega so it doesn't condensate.
(There is a possibility that I don't put the Arduino in the incubator at all, but it would be easier if I could).

The condensation is a real problem. Don't put an Arduino Mega inside an incubator. Why use such a big board? Perhaps a smaller board that can be potted in something might work, but perhaps others know about that.

Put the mega in a ziplock bag. Only have the wires stick out.

You could try a DIY conformal coating spray, read the label to see if it will do what you want.  If you have the budget then there are companies that will do a proper job, but it won't be cheep.  I would also worry about the temp.  You will need to make sure you can dissipate the heat from the board quickly and without messing up the temp of you incubator.

Why would it be so much easier to put it in the incubator?

I did the same this 2 years ago and had problems with co2 sensor mostly.
Which one do you use?

"-40 °C to 85 °C" for the processor, yes, for the other parts, who knows?
The board doesn't get that hot unless you are powering from like a 12V source, and then it's just the regulator that gets hot.
You could a spray-on conformal coat, Mouser.com carries them. Insert any wires into the headers you will use and cover any headers you may want to use before you spray, if you get coating down into the female headers you may have poor contact later on.
The ziplock bag idea sounds like a good start as a start, put some silicon along the seal to fill the holes where the zipper won't close right next to the wires.


text:
I2C call during Wire.requestFrom
Which I2C command happen during Wire.requestFrom(address, quantity)?
Is it correct that Wire put a Start condition, then 7-bit address appended with read bit? How would that be different from Wire.write(address)?

There is no Wire.write(address) in the Wire library. The function write() takes data and puts it into the library internal write buffer. It does nothing on the I2C bus.
For master write operation (sending from master to slave) the following commands are necessary:
Wire.beginTransmission(address);
Wire.write(data);
Wire.endTransmission();

Only the last of these commands does something on the I2C bus. It generates a Start condition, sends the byte consisting of the address (that we set in the beginTransmission() statement) and the direction bit, which is always 0 here, because these commands are meant for master write operation. Then it sends the data and ends the transmission with a stop condition. You cannot control, which value the direction bit has. The parameter of beginTransmission() is only meant to be 7 bit long. If you provide a bigger address, the function will simply cut the highest bit and issuing a write operation anyway.
For master read operation the action on the I2C bus happens inside the requestFrom() function. It sends a Start condition, followed by the address and the direction bit set to 1 (again you cannot control the value of the direction bit here). Then it reads the bytes, that are coming from the slave until all requested bytes were received. Then you can read the bytes from the library internal buffer with the Wire.read() function. Again this function does nothing on the I2C bus. It only interacts with the libraries buffer.

When the master reads data, you say that the slave can end the transmission with a nack. Check the i2c protocol please.

@Jot  Mhh, seems that you are right. This is not mentioned in the protocol. But I don't understand what happens, when the slave doesn't have enough bytes to send. Are the remaining bytes all read as 0xFF, since the slave doesn't drive the SDA line to low anymore?

Yes, that is what will happen. The master does not receive less bytes but also not more bytes than requested. As long as there is no error on the bus, the master gets the amount of bytes that it wants, regardless how many bytes the slave tries to send.

When you send an address with write(), it is a register address on the device, not the device address on the bus.
The device address is set with beginTransmition() and requestFrom().
If the device requires to set the register before requestFrom(), the register address should be sent with write() wrapped in beginTransmition() and endTransmition().
Example:
Wire.beginTransmission(I2C_ADC121);
Wire.write(REG_ADDR_RESULT); // send register to read, the 'result' register
Wire.endTransmission();
Wire.requestFrom(I2C_ADC121, 2);
byte buff[2];
Wire.readBytes(buff, 2); // read value of the 'result' register


text:
Tiny RTC module doesn't work properly when connected to an Arduino Uno together with 16x2 LCD
I am trying to make a digital clock using a tiny RTC, 16x2 LCD, and Arduino Uno. The RTC module works fine if 16x2 LCD is not connected to the Arduino. Both RTC and LCD are I2C modules and hence are using the same A4 and A5 pins of the Arduino. I have been informed that the I2C devices if connected in parallel should work. But, in this case, the clock doesn't show the time properly.

Have you checked that the i2c addresses are different? A schematic and minimal program that demonstrates the error would be useful.

Yes, I did and found that the addresses are different (LCD: 0x3F and RTC: 0x50 and 0x68). The addresses for RTC is reasonable since it has an EEPROM memory builtin.

Without more information we won't be able to help you.  Add a schematic and a minimal program that demonstrates the problem.

Thank you for your quick response. It was my fault that I pulled out the battery from the RTC module for a short time that ultimately reset the module.

An I2C scanner sketch can help to identify the actual addresses in use. I would use a sketch like on this page https://playground.arduino.cc/Main/I2cScanner or on this page http://gammon.com.au/forum/?id=10896&reply=6#reply6 . Or google 'arduino i2c scanner'.
Hook up the RTC by itself and run the scanner, then hook up the LCD by itself and run the scanner. The output will be on the serial monitor. If the devices have the same address, then that is your problem.
If one of the devices does not show up at all, then perhaps it is defective.

Thank you for the valuable information. I scanned the i2c device and found that they have different addresses.

I am incredibly sorry for my messy work. It all started when I pulled out the battery from the RTC. I was so frusted that I forgot to test the RTC module alone again. When I tried a different RTC, then that worked perfectly even with LCD. I found that the time can be adjusted as RTC.adjust(DateTime(F(__DATE__), F(__TIME__))); but, that also resets the time when the Arduino's reset button is pressed.

I find so often that I learn something unrelated to what I'm actually trying to do.


text:
Control multiple LEDs with multiple buttons
Problem 1: LED1 needs to be on only when button1 is held down. Right now it takes several presses to turn on and off and stays on.
Problem 1: LEDs 2,3,4 do not turn off with buttons 2,3,4. They are all turned off by button1, which is what I want, but I also need them to turn of with their respective button presses.
I need buttons 2,3,4 to light up LEDs 2,3,4 and stay lit until I press the respective buttons again OR button1 which turns off all lights, and the LED for button1 must only stay on when button1 is held down.
I am half way there with just a few minor problems. The first is LED1 stays on rather than when I hold the button1 down only. And the other problem is, it takes many presses to turn the LEDs on or off. I fixed this on 2,3,4 by removing the following code for each pin:
if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
  { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
    ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
  }

After I remove that code the LEDs light straight away and stay on until I press button 1 which is what I want. But I would also like LEDs 2,3,4 to turn off with their respective button press. With that code removed LEDs 2,3,4 no longer work independently of button1.
Full Code:
// set pins
const int buttonPin1 = 2;                 // Pin1's pushbutton
const int buttonPin2 = 4;                 // Pin2's pushbutton
const int buttonPin3 = 6;                 // Pin3's pushbutton
const int buttonPin4 = 8;                 // Pin4's pushbutton
const int ledPin1 = 3;                    // Pin1's LED
const int ledPin2 = 5;                    // Pin2's LED
const int ledPin3 = 7;                    // Pin3's LED
const int ledPin4 = 9;                    // Pin4's LED

// set variables
int ledPin1_status = 0;
int ledPin2_status = 0;
int ledPin3_status = 0;
int ledPin4_status = 0;

void setup() {  //initialize pins
  pinMode(buttonPin1, INPUT); // set PINn as INPUT
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(ledPin1, OUTPUT);   // set LEDn as OUTPUT
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
}

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

void loop() {
  if (digitalRead(buttonPin1) == HIGH) { // check if buttonPin1 was pressed (be sure to use a resistor?)
    if (ledPin1_status == 0) {           // check if ledPin1 was not already pressed
      digitalWrite(ledPin1, HIGH);       // turn ledPin1 on
      ledPin1_status = 1;                // 1 = on, set ledPin1_status to 1
    }
    else {
      digitalWrite(ledPin1, LOW);        // turn ledPin1 off
      ledPin1_status = 0;                // 0 = off, set Pin1_status to 0
      digitalWrite(ledPin2, LOW);        // turn ledPin2 off
      ledPin2_status = 0;                // 0 = off, set Pin2_status to 0
      digitalWrite(ledPin3, LOW);        // turn ledPin3 off
      ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
      digitalWrite(ledPin4, LOW);        // turn ledPin4 off
      ledPin3_status = 0;                // 0 = off, set Pin2_status to 0
    }
  }

  if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin2, HIGH);       // turn ledPin2 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin2) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin2, LOW);       // turn ledPin2 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin3 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin3, HIGH);       // turn ledPin3 on
      ledPin3_status = 1;                // 1 = on, set ledPin3_status to 1
    }
  }

  if (digitalRead(buttonPin3) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin3, LOW);       // turn ledPin3 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin4, HIGH);       // turn ledPin4 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

  if (digitalRead(buttonPin4) == HIGH) { // check if buttonPin2 was pressed (be sure to use a resistor?)
    { digitalWrite(ledPin4, LOW);       // turn ledPin4 on
      ledPin2_status = 1;                // 1 = on, set ledPin2_status to 1
    }
  }

names like buttonPin1, ledPin1 and ledPin1_status clutter up the code listing .... just use names like  button1, led1 and led1_status

First thing, you need to debounce your buttons. The fact that you
declared the (unused) variable debounceDelay suggests you have though
about debouncing, but you did not implement it.
Next thing, you should look for button press and release events.
That's when the button pin changes state from LOW to HIGH or vice
versa. It is not enough to check whether the pin is HIGH or LOW, you
have to check for the changes in state. This is usually called edge
detection.
With enough effort, you could probably do that yourself. However, to
make your life easier, you can use a debouncing library that does edge
detection, such as the quite popular Bounce2. This library provides,
for each button it debounces, a rose() method that tells you when the
input signal rose (i.e. transitioned from LOW to HIGH) and a
fell() method that tells you when it fell (transitioned HIGH
→ LOW). Using these methods, your problem can be coded in a fair
natural way. For example (not tested):
#include <Bounce2.h>

const int     BUTTON_COUNT = 4;
const int16_t DEBOUNCE_DELAY = 50;
const uint8_t buttonPins[BUTTON_COUNT] = {2, 4, 6, 8};
const uint8_t ledPins[BUTTON_COUNT] = {3, 5, 7, 9};

Bounce buttons[BUTTON_COUNT];
uint8_t ledStates[BUTTON_COUNT];

void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
        buttons[i].attach(buttonPins[i], INPUT);
        buttons[i].interval(DEBOUNCE_DELAY);
        pinMode(ledPins[i], OUTPUT);
        ledStates[i] = LOW;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

void loop() {

    // Update the debouncers.
    for (int i = 0; i < BUTTON_COUNT; i++)
        buttons[i].update();

    // When the first button is pressed:
    if (buttons[0].rose()) {

        // Light up the first LED.
        digitalWrite(ledPins[0], HIGH);

        // and turn off all the others.
        for (int i = 1; i < BUTTON_COUNT; i++) {
            ledStates[i] = LOW;
            digitalWrite(ledPins[i], ledStates[i]);
        }
    }

    // When the first button is released:
    if (buttons[0].fell()) {

        // turn off the first LED.
        digitalWrite(ledPins[0], LOW);
    }

    // When any other button is pressed:
    for (int i = 1; i < BUTTON_COUNT; i++) if (buttons[i].rose()) {

        // Toggle its state.
        ledStates[i] = !ledStates[i];
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

Edit: In order for the first button to only turn off LEDs 1 and 2,
the lines
// and turn off all the others.
for (int i = 1; i < BUTTON_COUNT; i++) {
    ledStates[i] = LOW;
    digitalWrite(ledPins[i], ledStates[i]);
}

should be replaced by:
// and turn off LEDs 1 and 2.
for (int i = 1; i <= 2; i++) {
    ledStates[i] = LOW;
    digitalWrite(ledPins[i], ledStates[i]);
}

Wow Edgar, what a great sketch, so neat, hopefully I can learn a lot from it, thanks. What methods are there to make windows recognise it as a controller? Is it code or windows I have to play with, or both.

How would I go about selecting only certain buttons to turn off with button1? Say I wanted to have button 4 independent.

@TRUEBRIT: 1. Sorry, I know nothing about Windows programming, which is out of topic here anyway. 2. In the section right after the comment “and turn off all the others”, instead of looping through buttons 1 through 3 (they are numbered from zero), you only turn off button 1 and 2.

I can't see how to do that?

@TRUEBRIT: See amended answer.

Thanks again Edgar. If I were to add other inputs such as a Rotary encoder, would the debounce library affect that?

@TRUEBRIT: This is unrelated to the original question.


text:
How do I include a file that is not a .h, .c or .cpp file?
I am using the ADF7030 on the breakout board (not motherboard) and I am trying to interface it with an Arduino Uno. I want to load the transceivers configuration file onto the chip using SPI. To do this, I need to include the ".cfg" file but when I use the C style array (as in the datasheet - code below) it says that it can't find the file in the .ino sketch.
const unit8_t Radio_Memory_Configuration [ ] = {
     #include "Settings_ADF7030-1.cfg"
}
How could I include this file?

I guess the Arduino IDE preprocessor is making it difficult for you. As it copies files to a build directory it might miss your specific configuration file. Try changing the file suffix to .h just to test this.

From looking at the arduino-builder source only files with the following extensions are copied to the build directory: .ino .pde .h .c .hpp .hh .cpp .s
So you will need to use one of those extensions.


text:
FIle not being found on sd card
I have some quite long code to copy a file from an SD to the same card, but under a different name. I have one version where the file names are built-in to the sketch, but to make it more portable, i have implemented a serial file selection system. There are 3 phases; choosing the input file, choosing the output file, and the copying. I have included checks to see if the files exist, confirmation for the names and so on. However, in the middle of my code, just before the copying phase, the input file disappears, and the arduino does not find it. It finds it in the first phase, finds the output file, but can't find the input file in the copying phase. SD.exists() and SD.open() both confirm this, but if i remove the sd card and put it into a computer, the file is there.
My code:
#include <SoftReset.h>
#include <SPI.h>
#include <SdFat.h>
#define csPin 4
#define roundTo 64

SdFat SD;
File sourceFile;
File outputFile;

int bufSize;
uint32_t lastPos = 0, timeLast, timeNow;
#define BAUD 115200
//make timeBetweenChars the time it takes (in milliseconds) between each char being transferred over serial, and make it at least one
unsigned long timeBetweenChars = max(1000 / (BAUD / 8), 1);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(BAUD);
  while (!Serial) {
  }
  Serial.print(F("Initializing SD card..."));
  /******************************************************************************/
  // see if the card is present and can be initialized:
  if (!SD.begin(csPin, SPI_FULL_SPEED)) {
    Serial.println(F("Card failed, or not present"));
    soft_restart();
  }
  Serial.println("Card initialized.");

  Serial.println(F("Files on card:"));
  SD.ls();
  //******************************************************************************
  //START OF INPUT FILE NAME
  //******************************************************************************
enterInputFileName:
  Serial.println(F("Enter input file name:"));
  while (!Serial.available()); // wait till serial available
  char inbuf[64];
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  byte pos = 0;
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    inbuf[pos] = Serial.read();
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for input file name
  char inputFileName[pos];
  //copy data from inbuf to inputFileName
  strcpy(inputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmInputFileName:
  Serial.print(F("Select file '"));
  Serial.print(inputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  char confirm = Serial.read();
  bool tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmInputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterInputFileName; break;
    case 'n': goto enterInputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(inputFileName);
  Serial.println("' as input file");
  if (SD.exists(inputFileName)) {
    Serial.println(F("File exists"));
  }
  else {
    Serial.println(F("Error, file does not exist. Please choose another file"));
    goto enterInputFileName;
  }
  //******************************************************************************
  //END OF INPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF OUTPUT FILE NAME
  //******************************************************************************
enterOutputFileName:
  //clear input buffer
  for (byte w = 0; w < (sizeof(inbuf) / sizeof(inbuf[0])); w++) {
    inbuf[w] = '\0';
  }
  Serial.println(F("Enter output file name:"));
  //wait for some chars to arrive
  while (!Serial.available());
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  pos = 0;
  //found here Serial.print(SD.exists(inputFileName));
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    //file found on first loop, but not after that
    // found here Serial.println(SD.exists(inputFileName));
    inbuf[pos] = Serial.read();
    //not found here Serial.println(SD.exists(inputFileName));
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  //input file not found here
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for output file name
  char outputFileName[pos];
  //copy data from inbuf to outputFileName
  strcpy(outputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmOutputFileName:
  Serial.print(F("Select file '"));
  Serial.print(outputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  confirm = Serial.read();
  tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmOutputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterOutputFileName; break;
    case 'n': goto enterOutputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmOutputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(outputFileName);
  Serial.println("' as output file");

  if (SD.exists(outputFileName)) {
    Serial.println(F("File already exists. Overwrite? Y/N"));
confirmOverwrite:
    while (!Serial.available()); // wait till serial available
    confirm = Serial.read();
    tooManyChars = 0;
    // wait for the next chars
    delay(timeBetweenChars);
    while (Serial.available()) {
      //read next char
      char extra = Serial.read();
      //if it isn't a newline or carriage return
      if (extra != '\n' && extra != '\r') {
        //too many characters entered
        tooManyChars = 1;
      }
      //wait for next char
      delay(timeBetweenChars);
    }
    /******************************************************************************/
    if (tooManyChars) {
      Serial.println(F("Enter 1 char"));
      goto confirmOverwrite;
    }

    //if only 1 char entered
    bool overwrite = 0;
    switch (confirm) {
      case 'Y': overwrite = 1; break;
      case 'y': overwrite = 1; break;
      case 'N': goto enterOutputFileName; break;
      case 'n': goto enterOutputFileName; break;
      //invalid char entered
      default: Serial.println(F("Enter Y/N")); goto confirmOverwrite; break;
    }
    if (overwrite) {
      Serial.println(F("Removing output file"));
      SD.remove(outputFileName);
    }
  }
  Serial.println(F("Creating output file"));
  outputFile = SD.open(outputFileName, FILE_WRITE);
  outputFile.close();
  //******************************************************************************
  //END OF OUTPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF COPYING
  //******************************************************************************
  //read source and write to output
  sourceFile = SD.open(inputFileName);
  timeLast = micros();
  //debug line
  Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
  if (sourceFile) {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(F("Copying"));
    while (sourceFile.available()) {
      //make buffer size 50% of free ram, or amount of bytes left if smaller
      int ram = round((freeRam() * 0.5) / roundTo) * roundTo;
      bufSize = min(ram, sourceFile.available());
      //round to nearest value of roundTo
      bufSize = round(bufSize / roundTo) * roundTo;
      byte data[bufSize];
      sourceFile.readBytes(data, bufSize);
      lastPos = sourceFile.position();
      sourceFile.close();
      outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
      outputFile.write(data, bufSize);
      outputFile.close();
      sourceFile = SD.open(inputFileName);
      sourceFile.seek(lastPos);
      //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
      printStats();
    }
    sourceFile.close();
    outputFile.close();
    Serial.println(F("Finished"));
    unsigned int sec = millis() / 1000;
    unsigned int mins = sec / 60;
    sec -= mins * 60;
    Serial.print(F("Time taken: "));
    Serial.print(mins);
    Serial.print(':');
    Serial.print(sec);
    Serial.print(F("Speed: "));
    Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
    Serial.print(F(" KB/s"));
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening files");
    Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
    SD.initErrorHalt();
  }
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);
}

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void printStats() {
  timeNow = micros();
  uint32_t timeTaken = timeNow - timeLast;
  float sent = sourceFile.position() / 1000.0;
  float fileSize = sourceFile.size() / 1000.0;
  float left = fileSize - sent;
  float speed;
  speed = 1000000UL / timeTaken * bufSize;
  speed /= 1000;
  unsigned int sec = millis() / 1000;
  unsigned int mins = sec / 60;
  sec -= mins * 60;
  int estSec = (left / speed);
  int estMin = estSec / 60;
  estSec -= estMin * 60;
  Serial.print(F("\tSent (KB): ")); Serial.print(sent);
  Serial.print(F("\tLeft (KB): ")); Serial.print(left);
  Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
  Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
  Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
  Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
  Serial.print(F("\tBuf: "));       Serial.print(bufSize);
  Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
  //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
  Serial.print('\n');
  timeLast = micros();
}

My serial output(I chose Nova.mp3 as input file and output.mp3 as output file):
Initializing SD card...Card initialized.
Files on card:
output.mp3
Nova.mp3
Eclipse.wav
Enter input file name:
Select file 'Nova.mp3'? Y/N
Using file 'Nova.mp3' as input file
File exists
Enter output file name:
Select file 'output.mp3'? Y/N
Using file 'output.mp3' as output file
File already exists. Overwrite? Y/N
Removing output file
Creating output file
Exists(I,O): 01
error opening files
Exists(I,O): 01
No error found.

I know i am not running out of memory, and have no compiler errors, but i have no clue what is going wrong. Is it possible I have put in some unnecessary code? Also, if it was possible to have multiple files open at a time, would i spped up my read/write speed?

you char array for inputFileName is one char shorter then needed. if 0 is at pos you need to allocate and copy pos + 1 chars because the indexing starts at 0. (btw: your code is very ineffective)

I know indexing starts at 0, and if you didn't notice, i actually add 1 to pos at the end of the loop, so the array should be long enough. And how is it ineffective? do you mean inefficient?
Edit: this actually made my code start copying, will update if it finishes successfully.

too much code for the task

How should i compress it? i can't do the copy loop as simply as i'd like, because only 1 file can be opened at a time, and i put the file selection confirms in because sometimes people make typos. what can i make smaller

"As of version 1.0, the library supports opening multiple files." https://www.arduino.cc/en/Reference/SD

the code for filename input is repeated

I'm using SDFat not SD

The problem is that you have the char arrays for zero terminated c-string one char shorter then needed. I see you assign the terminating zero to inbuf[pos] and then you allocate pos chars for the filename and copy pos count of characters. That leaves out the terminating zero and the c-string of the filename is not terminated by 0 and continues in memory with random content.


text:
The Arduino IDE can’t find my Arduino Uno
My Arduino has all of its LEDs on. The Rx, Tx and L LEDs are all on and my computer can’t see it (it's an SMD edition).

It can have many reasons, but you can try the following:
First time use?

Check if you need to install a special driver for CH340

Environment/Software problems

Try another USB port
Change USB cable
Restart Arduino IDE
Restart computer
Reinstall Arduino IDE

Hardware problems

Test using another Arduino
Test using another computer/laptop
Replace USB cable
The Arduino is (partly) broken, nothing much to do here

The USB interface chip controls the Rx & Tx lights.  I suspect you fried it.
Does the '328P feel warm or hot to the touch? That's usually a sign that it has been damaged.

Is it an "official" Arduino purchased from their website? If it isn't, chances are you need to install CH340 drivers for your computer before the Arduino will be recognized. Drivers can be found here Have you successfully used this device with your computer before?


text:
Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead?
I have some boards with the atmega32u4 that they were working perfectly before. I'm using an unnoficial UNO board to program them via ICSP. To power the uC I'm using two lithium batteries and a step-down converter to drop it to 5 V.
This started happening when I tried to upload code via ISCP when the target chip was not powered by mistake.
This is my error message:
Arduino: 1.8.5 (Windows 10), Placa:"Arduino Leonardo"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

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.

What I've already tried:

Different programmer (another Uno board);
Uploading to a proper Leonardo board via ICSP, it worked;
Uploading to another of my boards via ICSP, it worked;
Running with the portable Arduino version;
Check if the chip is being powered with 5 V;
Changed wires and checked the connections;
The chip does not get hot;

I've been around this two days straight, any help would be much appreciated.

Have a look at this question and answer: Have I bricked my Arduino Uno? Problems with uploading to board

Mostly this error is due to connections/powering issues (as already mentioned in your output ).

Check connections, especially power and ground also check the
resistance between Vcc and GND of your target MCU. (If it's less than
100ohm that means something is off in your circuitry or your MCU is
already fried.)
Check if your MCU is actually getting enough power (voltage and current) also check if it's getting excess voltage.
Make sure there is proper "common grounding" done between devices.
If you are sure that the above points are checked and you still get the error try the override flag -F (avrdude through shell/command-line) and if you are still not able to upload try the manually changing the address (not recommended ) in your arduino's library so that it matches with the signature it's receiving.
Finally try using a direct USB interface with atmega32u4 as atmega32u4 supports it and upload the bootloader again through an old software called Flip after that try again.

After all this if you are not able to upload then probably your MCU is dead and it might be due to an unnoticed wrong power connection or short circuit or unintentional fuse reconfiguration (highly unlikely).


text:
Is there a real alternative now to using GSM for data sending?
I would like to create an Arduino system that sends the temperature in a place outdoors to a server.
I've read in Internet forums that there might be alternatives to GSM and GPRS technology for sending data remotely, but I'm not sure about them. In absence of WiFi, is GSM the best technology today, even that you have to use the SIM plan to use it?

what's the range? can you use LORA?

the range could be km-s and I don't live in Germany.

i don't know what germany has to do with anything, but lora can go several KMs, easily

ok, sorry, I was totally wrong. I thought that it only was valid in Germany. I'm trying to send some temperature data to a remote server. I'm seeing some tutorials in Arduino that do that, so I'm going to consider it. Do you see any problem in using LoRa for my application?

GSM (or more realistically now, LTE) is really the only option.
Simply put: you need some method of accessing the internet, and unless you create your own local infrastructure that means using the mobile phone system. It's the only system that is virtually everywhere and doesn't require you to install your own communication system.
So that means some modem device that can communicate with the mobile phone system. GSM is what it used to be, although some mobile companies are now deprecating the GSM system and only really providing UMTS (3G) and LTE (what will eventually be 4G), but LTE modems are quite expensive still.
So yes, you need a SIM to do it. You can't access a mobile phone network without one.
One option that could be a cheaper possibility would be to get a cheap second hand smartphone off eBay (or dig out your old one from the bottom of the desk drawer) and use that as your own mobile WiFi hotspot. Your Arduino device connects to the phone with WiFi, and the phone connects to the UMTS or LTE network using a cheap PayG SIM.

LoRA is a technology that is gradually becoming more popular and allows long range wireless communications at low power and low cost. There are areas where LoRA is becoming available, such as in Munich. Should LoRA become available in your area, or should you invest in your own infrastructure, that could become a viable alternative to using the mobile phone network.

Sigfox and NB-IOT are also two more technologies.

@MaximilianGerhardt So write an answer detailing them. Personally I have never heard of them.


text:
Resistors on LCD - does a small difference matter?
I recently have tried to connect an LCD to my Arduino Uno. The tutorial
tells me I need a 220 Ohm resistor, but the only ones I have are 330 Ohm. Does it matter?
Here's the Fritzing diagram by the way:

You can use the 330 ohm resistor. If the display's backlight is not bright enough, you could add a second 330 ohm resistor in parallel with the first one.

No, it doesn't matter. That resistor is just for the backlight LEDs. The larger the resistor the dimmer the backlight will be.  As @VE7JRO suggests, you can always put two 330Ω resistors in parallel, which will halve the resistance to 165Ω, which will give a brighter backlight.

It works! But when I power the Arduino through USB, the pixels are hard to read when looking straight in (this is not the case for when I use my battery pack with 6 x 1.2V rechargables). Maybe it's a problem similar to that in https://arduino.stackexchange.com/questions/22083/arduino-lcd-changing-contrast-only-makes-black-boxes-less-readable-i-e-less-in. Anyway, I an send you pictures if you want

Just adjust your contrast.

With the potentiometer? I've tried - I doesn't work (plus I've also tried s 330 Ohm resistor and a 470 Ohm resistor). By the way, it isn't a huge problem. I can always use the battery pack

Potentiometer adjusts contrast. Check your connection. It's pins should go to (left)Battery+, (middle)V0, (right)Battery-. This creates a voltage divider and turning it's knob changes voltage on (middle)V0 pin and it informs the LCD controller how to set the contrast. And about the resistor you can even ignore it and just connect LCD directly to Battery+.

Nope. The lcd has backlight led which needs to powered separately. More resistance, dimmer it will be. Higher voltage decreases life span of your lcd backlit.


text:
Arduino and AVR Serial Communication over USB
I have a Arduino Uno Rev3 and I would like to use a AVR development toolchain to write a program that performs serial communication over USB.
Doing this using the Arduino IDE is fairly simple:
void setup() {
   Serial.begin(9600);
}

void loop() {
   int i;
   while(1) {
      Serial.write("hello\n");
      delay(5000);
   }
}

Then from Linux, I can simply read from /dev/ttyACM0 and every 5 seconds I get "hello\n".
I found a blog post titled Simple Serial Communications With AVR libc that explains how to perform serial communication using an AVR development toolchain. The simplified version of the above Arduino sketch is below.
#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#ifndef BAUD
#define BAUD 9600
#endif

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>

void uart_init() {
    // Upper and lower bytes of the calculated prescaler value for baud.
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

    // Configure data frame size to 8-bits.
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

    // Configure to enable transmitter.
    UCSR0B = _BV(TXEN0);
}

void uart_putchar(char c) {
    // Wait until the register to write to is free.
    loop_until_bit_is_set(UCSR0A, UDRE0);

    // Write the byte to the register.
    UDR0 = c;
}

void uart_putstr(char *data) {
    // Loop until end of string writing char by char.
    while(*data){
      uart_putchar(*data++);
    }
}

int main() {
    uart_init();

    while(1) {
        uart_putstr("hello\n");
        _delay_ms(5000);
    }

    return 0;
}

The problem is, this doesn't actually work. I can build and flash the ATmega328p but reads to /dev/ttyACM0 block forever. I suspect what is happening is that the serial communication is occurring on some pins and not over USB, but I am not sure.
Anyone have any idea on how I can emulate Serial.write using an AVR development toolchain and have the output be written over USB?

8000000UL my Uno board has a standard 16MHz crystal on it. Besides, what program / command do you use for reading out data over dev/ttyACM0?

I tried 16000000UL as well, still didn't work. I originally switched to 8000000UL because the on-board LED did not blink correctly with 16000000UL.

As for reading /dev/ttyACM0, I've written a simple program using the following library: http://github.com/pkg/term. However, I imagine cat or tail -f would show the same results.

Why is this being closed as off-topic? The help centre tells that questions about other IDEs, clones/counterfeits/derivatives, and other coding languages for Arduino are OK.

Turns out the problem was with my Makefile. avr-gcc was missing the -mmcu=atmega328p flag. Once I added that and changed F_CPU to 16000000UL everything works.


text:
Datalogger with interruputs
I'm trying to do a data logger. Writes into SD card has to stop when millis()=1000. Maybe I have a problem between millis() and my interrupt, because datalogger doesn't stop after millis()=1000. I'm working with Arduino Mega.
#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;

void setup() {
  DDRA = B11111111;
  cli();//stop interrupts
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 10000khz increments
  OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);
  sei();//allow interrupts
  //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}

ISR(TIMER0_COMPA_vect) {
  cuenta++;
  if (cuenta > 9) {
    PORTA = ++contador;
    cuenta = 0;
  } else {
    PORTA = 0X00;
  }
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis <= interval)
  {
    String dataString = "";
    for (int analogPin = 0; analogPin < 1; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString = String(sensor);

      if (analogPin = 1) {
        dataString += ",";
      }
    }
    File dataFile = SD.open("datalog2.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    else {
      Serial.println("error opening datalog.txt");
    }
  }
}

The millis() function is based on a counter which is incremented by
the Timer 0 overflow interrupt. Since you reconfigured
that timer to never overflow, that counter is not incremented anymore.
If you want to configure an Arduino timer for your own purposes, you
have to either:

use any timer other than Timer 0, or
loose the Arduino standard timekeeping functions: millis(),
micros() and delay().

I would favor the first option, especially on the Mega which has quite a
few spare timers.


text:
9x servo on Arduino Nano?
I saw this project with multiple servos: In Servo We Trust! Let's control 135 servos with a single Arduino! I wanted to miniaturize this project.
BUT instead of triangles i will use SQUARES.
:EDIT: summing UP
For now project stops, not forever. I bought 9 servos on aliexpress and im waiting for them to be delivered. Also, im making a 3D project in AutoDesk Maya 2018, planning and will sbow you the results soon how im gonna make it work.
I was thinking about adding 1 more servo and hc sr06 distance sensor. I was thinking about the sensor will detect person, servos and mirrors will also follow the person. But idk if im gonna make it to the final project.

I bought arduino nano that will be powered from the battery
All servos will be powered with electricity from the wall 5V 5A.The servos wont be on heavy load so it will be enough i think.If any problem occurs I will use 10A.

ALSO SORRY for not editing this POST earlier.
I would like to thank everybody for giving me such a great advices, I will post my AutoDesk project soon.

I'm afraid that with PWM controler I won't be able to do that.

Chances are that any PWM controller is going to let you control each output independently.
According the the servo library documentation, the library can handle up to 12 servos on a single Arduino, so your project should be feasible. It will however reduce the number of PWM pins available from 6 down to 4.

Will a 9V battery power all these servos?

No! Not a chance.
Typical 9g servos consume 150 mA without any load, and stall at ~700-900 mA. A typical 9v has ~500 mAh capacity, and most data sheets show loads of ~100-150 mA max. Your 9v might be able to supply a few amps for a few seconds before they heat up and slow down.
If your load is very light 9 servos will consume ~900 mA; an ideal 9v would last at most 30 min with this load, but real batteries aren't ideal and will heat up and loose efficiency.
Near maximum load your 9 servos will draw ~7000-9000 mA, well beyond the capabilities of a 9v. However those numbers are for 5v so you could cut them all in half.
If you used an appropriate 5v step-down DC-DC supply you might be able to power all 9 servos for a few seconds before the batter overheats and gives up.
If you powered them directly, the servos will have to dissipate more heat, and will draw extra power, could damage the servos if the batter could supply enough juice.

Yes, I know. But i need only 9 servos and PWM controller can operate on 16. From this forum: http://rcarduino.blogspot.com/2012/04/servo-problems-with-arduino-part-1.html, I know that i need separetly battery to power arduino and servos. Let me do a schematic of what im thinking. I'll post it in a minutes.

Here's the photo. In nano there's 10 digit pins. I'll take 9 and control each servo separately. Will it be fine? What about the voltage to power the servos? 9V battery will do?

@LazyArtistSQuex 9g servos don't take much power; a 9v should power at least one, but I don't know about trying to power 9 at once with a single 9v, n.b. the operating voltage of most 9g servos is 4-6v

If the servo operates on 4-6V, doesn't 9V will be too much for a single one? How about I buy this only to power 9 servos? https://pl.aliexpress.com/item/1pc-3S-11-1V-1500mAh-35C-Lipo-Battery-XT60-T-Plug-for-RC-Car-WLtoys-V950/32827187894.html?spm=a2g0s.13010208.99999999.293.110d3c006Q80BG. I've read that one servo takes 500mA. So for 9 will me 4,5A. I can not find information how many amps this battery provides.

@LazyArtistSQuex it's not the voltage that's the problem, its the capacity. The battery you linked claims to be 35C, so 1.5 aH * 35C = 52.5 A max discharge, which would drain that batter in under 2 min; If the specs claimed are accurate.

Now i understand. Sorry, it's 3 a.m. and i've been thinking of this for nearly 3h.
So it's not all about the voltage. I can use 5V battery but i need higher capacity. If i use 10'000 mAh the servos will drain it in about 13 minutes. It's okay but battery like this costs around 20$.
Another option might be power directly from the electricity from the outlet. Of course i suppose I'll need voltage converter from 230V to 5V. Will this work?

@LazyArtistSQuex a 10 Ah batter will run a 10A load for an hour, that would only occur under the heaviest load for your servos stall==maximum load; under a light load, a 10 Ah Battery could last 10 hours or longer for 9 servos @ ~ 1 A total, so it totally depends on the load the servos will experience; yes wall power will work you will need a power supply, of course

Okay. So let's make things clear. I don't need PWM servo controller, i can only use arduino nano for 9 servos.
Power problem:
I power arduino nano with the battery. I power servos with the wall electricity, but i need voltage converter from 230V to 5V and it needs to be at least 9-10A. The servos will not be on heavy load. Just small turns like on the video from the project.

@LazyArtistSQuex for a light load you can get away with less than 10A, 5A may suffice for a light load, 2A for a very light load.

Or use two 5A supplies. Couple like these  http://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS

@CrossRoads just out of curiosity how am I gonna connect TWO of this cables (how to plug in them). I was thinking about this: https://www.shemeck.pl/851-rs-25-5-zasilacz-impulsowy-25w-5v-5a.html?gclid=Cj0KCQjwnNvaBRCmARIsAOfZq-0V5hE3NSN0M3dAXipw7TWMhuBYspNMe47AFRVXle7X0Jt_RA42adUaAthOEALw_wcB as a power for servos.

Here are the specifications of the SG90 (from FEETECH (Fitec) FS90 9G Mini Servo with Accessories)

The FG90 is similar in specification to the SG90. From the website:

The FS90 is a 9 g analog servo from FEETECH (formerly known as Fitec) which is similar in form and function to the Towerpro SG90. The specifications state that this servo has a 120° operating angle for standard servo pulses between 900 µs and 2100 µs. As with most servos, the pulse range can be expanded to achieve an expanded operating angle, but the limits of which are not specified by FEETECH.

From this answer to Power supply circuit for powering SG90 servo. How to handle high current requirements?, lets assume each servo (best case) needs 250 mA, as you state that the load per servo is relatively low.
Let's say that the Nano requires 280 mA, see this answer to What is the maximum power consumption of the Arduino Nano 3.0?
Using a single 5V supply to power both servos and Arduino. The current rating needs to need at least:
I = (9 x 0.25) + 0.28
I = 2.53 A

Or power rated
P = I x V = 2.53 x 5
P = 12.65 W

You probably want more than that, so get a 5 V 5 A supply to be on the safe side. So, no, a battery will not suffice.

I wanted to make separetly power for nano and servos, but this way will work too.

I wanted to buy these: https://pl.aliexpress.com/store/product/4pcs-PKCELL-1-2V-4-5A-2100mAh-NiMh-Rechargeable-Batteries-Flat-Top-For-Soldering/918700_32822951027.html?spm=a2g17.search0104.3.44.7b6621e1Ks4oz8&ws_ab_test=searchweb0_0,searchweb201602_4_10152_10151_10065_10344_10068_10342_10343_10340_10341_10696_10084_10083_10618_10304_10307_10820_10821_10301_10843_10059_100031_10103_10624_10623_10622_10621_10620,searchweb201603_13,ppcSwitch_5&algo_expid=774f7647-2d15-445d-af5c-46e6fb9b3e5a-6&algo_pvid=774f7647-2d15-445d-af5c-46e6fb9b3e5a&priceBeautifyAB=0.

4*1,2V=4,8V and 8400mAh and 5A. Will it be enough?

Or poeer from the wall and converter from 230V to 5V and 5A. This seems like a cheaper option and more reliable. It costs like 7$. So can i use this power to the arduino nano and power sergos from the Vin pin 5V? The 5A wont be to much for arduino nano? If not ill use just ppwer from the battery to the nano and servos will be povered from the wall

@LazyArtistSQuex you can power them separately (with sufficient power supplies) but you must connect the ground lines together (only the ground) to ensure everything has the same reference for the voltage.

@LazyArtistSQuex: Nano runs off 5V. The Nano will draw as much current as it requires, so you could use a 5 V 20 A supply and the Nano will be fine. The supply does not force the current into the Nano (or any device), the device pulls what is needed from the supply (and no more). Only the voltage of the supply has to match (and not exceed) the (maximum) voltage requirements of a device (i.e. the Nano). The supply only has to provide the minimum required current, in order for the device to operate correctly but it can provide more and the device will not break. Does that make sense?

Thank you for your answer. It seems more clear now. I edited my post;))

You can drive upto 20 servos on an Arduino Nano - here's the EXCELLENT software for this: http://www.lamja.com/?p=504
Most servos can run well using high voltages (e.g. 9v) while still accepting PWM signals much lower (e.g. 3.3v) - here's a video showing that working fine:  https://youtu.be/9ZCiQgjcx3k
See Greenonline's answer table (or servo datasheets) to work out your power budget.  9v will work, but is probably more than the servos would like: 6v is more usual.

Cheapest way is that you should buy couple of LM7805 wire it in parallel now power arduino and other servos from this 7805. Connect pwm pins of servos to the nano.
Voltage regulator built inside arduino cant provide much current to all servos.
Also connect ground of all of your power sources together.

Servos don't use PWM, not really. What they need is a pulse that is ~ 1mS wide every 20mS (50 Hz) to turn full one direction, ~ 1.5mS wide to be centered, and about 2mS wide to turn fully the other direction.  Or centered, +/- ~ 60-75 degrees or so.
(0.9mS to 2.1mS per the data above).

So, what you are telling me I won't be able to connect 9 servos directly to arduino nano? https://www.google.com/search?newwindow=1&biw=1366&bih=673&tbm=isch&sa=1&ei=JX1XW-u8OdGWsAejsZW4Cg&q=arduino+nano+pwm&oq=arduino+nano+pwm&gs_l=img.3..0l2j0i30k1l7j0i8i30k1.8231.8911.0.9245.4.4.0.0.0.0.333.566.2-1j1.2.0....0...1c.1.64.img..2.2.565...0i67k1.0.yGDezZalT9M#imgrc=Et2rxIh3mJeo-M:

The Servo.h library will control up to 12 servos on a 328P based board, such as the Nano. But it's not using PWM to do to it.  You will need a decent power supply to power them if you plan on moving 9 at once for any length of time.  Perhaps two or three of something like this http://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/ and don't forget power connectors http://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL  Be sure to connect all Gnds together.

Thanks for the power supply answer. So arduino nano will be suitable for my project or use another board?

12 > 9, so yes, it will suitable.

Great, now i need the parts to come. Also i need to design the case that will hold all components (i will make it from wood). Will update in short time. Thanks Sir.


text:
Flashing NodeMCU with .ino file?
I'm brand new to the Arduino world. I recently purchased a NodeMCU in order to have it act as a sort of foothold to get into Arduinos as it's something I've always wanted to do. However, it was only after I had received the NodeMCU that I realised that there was no default option in the Arduino IDE to flash to a NodeMCU and soon found out that this is because the NodeMCU is in fact not an Arduino and therefore has its own proprietary flashing software for .bin files. This initially confused me as an outsider as I assumed all devices of that nature must be Arduinos.
I recently came across a Homebridge plugin by affix called homebridge-mcu-lamp which uses a NodeMCU running an HTTP server to control a relay. Interestingly, the script he has included in the repository which he claims to have running on his NodeMCU is a .ino file which really confused me.
My question is: how would I flash a .ino file to a NodeMCU like the one mentioned above as I have no experience with .bin files and would much more value to treat the NodeMCU as an Arduino instead (i.e. programming in C++)?
I understand this may sound like a very simple/dumb question for most of you on this forum but it is something that has had me stumped for days and would really appreciate some guidance on.
I would also find it useful if someone could explain to me the difference between a NodeMCU and an ESP8266 as I see the two words being used interchangeably when referring to the same looking board.
This is what my NodeMCU looks like:

esp8266 is a chip under the metal shield of the esp-12 module. esp-12 module is the board glued to the NodeMcu board

Last question first: The ESP8266 is the main IC on the NodeMCU board.
This is similar to the idea that an ATMega328 is the IC on Arduino Uno.
A normal 'clean' Arduino IDE install can work with an Uno ('flash with an INO'), but not with an ESP8266 based board. For this, you will need the ESP8266 addon for the Arduino IDE, after which, the NodeMCU board is available as an option.
This page documents the ESP8266 addon:
https://github.com/esp8266/Arduino
Long story short, open preferences (File -> Preferences) , under Additional Board Manager URLs, add http://arduino.esp8266.com/stable/package_esp8266com_index.json
Click on Tools>Board>Board Manager (assuming you have Arduino IDE 1.6.4 or later) and search for ESP8266 and install the option that includes NodeMCU.

Thank you so much for your reply, that was exactly what I was looking for! Last question; apart from having to install the ESP8266 adding separately, will everything else work exactly the same as if it was an Arduino board (I.e. will the flashed software work exactly the same without any adjustments? Thank you once again!

Sorry, quick question, which buttons do I need to hold down when flashing from the Arduino IDE to the NodeMCU?

unless the nodeMCU is defective or a prototype, you should not need to hold down any buttons to flash from the arduino IDE

@dandavis Perfect, thank you so much for your help!

@Tom, there might be some subtle differences between how a 'proper' Arduino board like an Uno might behave compared to the NodeMCU, but this will depend on the function or library you are trying to use. Most 'core' Arduino functions should work very closely. The page I linked above is probably the best reference for this sort of thing.

@user85471 Thank you for the information, I've successfully been able to flash my NodeMCU with the method you referred to above so thank you very much! I haven't run into any sort of compatibility problems yet but I'll be sure to refer to the official documentation if I experience any sort of unexpected differences. Thanks! :)