Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

C# help


  • Please log in to reply
35 replies to this topic

#1 Ruff

Ruff

    New Member

  • Members
  • Pip
  • 9 posts

Posted 06 March 2011 - 08:12 AM

Hello, I'm new @ programming Microcontrollers. I played a little bit with an Arduino of my friend and now I bought an Netduino Plus with bags of electronical stuff. I recently programmed in other languages like Java, PHP, VB.Net or C. If I have a look at C# I'm getting a bit confused. Sometimes I'm expecting Java syntax but find VB ( i.e. foreach loop ). Sometimes it seems really mixed up (i.e. getters and setters == property? --> look like java, behave like VB). Looking for a List and find ArrayList, but without the advantages of generics? I can't believe I can only put 'Objects' into these List. Another Problem: I tried to write a simple Class which takes Enum.Pins in its Constructor to instantiate OutputPorts. Then I instantiate this Class in a static Context above static void main() in program.Class to use it in an Interrupt Event which is thrown by onboardSwitch. This program compiles but never returns from Class Constructor! Message is something like: "'this' is not accessible in a static context". Do I have to declare every OutputPort Property of that class static, too? Can someone of You point me a good tutorial especially about .Net Micro or for VB Developers. I think didn't need to learn everything from scratch.

#2 Nicolas Dorier

Nicolas Dorier

    Member

  • Members
  • PipPip
  • 24 posts

Posted 06 March 2011 - 10:31 AM

MicroFramework is really small, so the microframework does not support generics. What you need before hacking your netduino is to learn basic OOP principle in C# .NET 4.0 (not the micro framework version). Here is what you need to know, just google every bullet point or buy a certification book. http://www.microsoft...?id=70-536#tab2

#3 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 06 March 2011 - 03:46 PM

Ruff, I really think that C# is much more like Java, instead of VB. If you have some Java experience, then it won't be hard to write C#. About generics as other really useful stuffs, the problem is that you're using a minimum subset of the .Net framework, which has to be working on a small device (no ram, no flash). I actually did't understand well what's the problem with the static class, but -of sure- if you declare a static class, you cannot instantiate it: that's because you cannot use the "this" accessor that is for instances. If you wish to post your code (or part of), we may help you with some tip. Cheers Mario
Biggest fault of Netduino? It runs by electricity.

#4 ItsDan

ItsDan

    Advanced Member

  • Members
  • PipPipPip
  • 101 posts

Posted 06 March 2011 - 04:04 PM

C# may be more like java syntax but it's nearly identical to VB.NET, in that it runs on the same framework. Almost all code translates line for line from one to the other, and it's especially true on the microframework where fewer 'advanced' features are implemented.
Follow the adventures of the Box of Crappy Surplus

Total BOCS Traveled Distance: 9708 miles | States Visited: 5
Track the Box

#5 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 06 March 2011 - 06:24 PM

@ItsDan: please, don't mix the language with the libraries/framework. The language (C#) is very similar to Java and compiles to IL opcodes. That's the same for VB.Net, F#, IronPython and others. The fact is you take advantage of the .Net framework libraries which are the MS "default". However, you may write a C# compiler for the Oracle (former Sun) libraries. In the case of Net Micro Framework, the language is C# 4, but the libraries are a little subset. When the compiler tries to translate some feature of the C# (e.g. generics), fails because there's not any valid reference. Cheers Mario
Biggest fault of Netduino? It runs by electricity.

#6 Ruff

Ruff

    New Member

  • Members
  • Pip
  • 9 posts

Posted 06 March 2011 - 07:23 PM

Thats really funny:
"C# may be more like java syntax but it's nearly identical to VB.NET"
Vs.
"Ruff, I really think that C# is much more like Java, instead of VB."
since it proofs my feeling.
Sorry for this confusing question, I came back from a 13 hour netduino session and was too tired and wasn't able to express myself properly.
I think I know well about OOP patterns, so these link from microsoft is a little needles for me.
so first: I understand that generics may be too much overhead for micro.net. So am I able to use any kind of Collection?
to the other problem with my static class: Its not a static class, it was only declared static in program.class. It should encapsulate the patterns for a 7-digit-led. Here is the code:
public class Program
    {

        static Config config = new Config(Pins.GPIO_PIN_D10, Pins.GPIO_PIN_D8, 
                                          Pins.GPIO_PIN_D11, Pins.GPIO_PIN_D6, 
                                          Pins.GPIO_PIN_D7, Pins.GPIO_PIN_D1,
                                          Pins.GPIO_PIN_D13, Pins.GPIO_PIN_D2);        
        public static void Main()
        {
             
            config.MaxNumber = 9;
            InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth)
            button.OnInterrupt +=new NativeEventHandler(button_OnInterrupt);
            Thread.Sleep(Timeout.Infinite);
        }

        static void button_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            if(data2 == 0)
            {
                 config.turnNextNumberOn();

            }
        }
}

public class Config
    {
        public OutputPort segmentA;
        public OutputPort segmentB;
        public OutputPort segmentC;
        public OutputPort segmentD;
        public OutputPort segmentE;
        public OutputPort segmentF;
        public OutputPort segmentG;
        public OutputPort segmentPoint;

        public int MaxNumber
        {
            get { return MaxNumber; }
            set
            {
                MaxNumber = value > 9 ? 9 : value;
            }
        }

        private int ledNumber;
        private bool state;
        
        public Config(Cpu.Pin a, Cpu.Pin b, Cpu.Pin c, Cpu.Pin d, 
                      Cpu.Pin e, Cpu.Pin f, Cpu.Pin g, Cpu.Pin point)
        {
            segmentA = new OutputPort(a, false);
            segmentB = new OutputPort(b, false);
            segmentC = new OutputPort(c, false);
            segmentD = new OutputPort(d, false);
            segmentE = new OutputPort(e, false);
            segmentF = new OutputPort(f, false);
            segmentG = new OutputPort(g, false);
            segmentPoint = new OutputPort(point, false);
            state = false;
            ledNumber = -1;
            MaxNumber = 9;
        }

        public void turnNextNumberOn()
        {
            int next = ledNumber + 1 <= MaxNumber ? ledNumber +1 : 0;
            turnLedNumber(next, true);
        }

        public void turnLedNumber(int number, bool state)
        {

            if (this.state && state == true)
            {
                turnLedNumber(ledNumber, false);
            }
            
            switch (number)
            {
                case 0:
                    turnNumberZero(state);
                    break;
                 //.......
             }
             this.state = state;
             this.ledNumber = number;
        }

        private void turnNumberOne(bool state)
        {
            segmentB.Write(state);
            segmentC.Write(state);
            
        }

        private void turnNumberZero(bool state)
        {
            turnNumberSeven(state);
            segmentD.Write(state);
            segmentE.Write(state);
            segmentF.Write(state);
        }

        //......
}

I can't see the Problem at all with this code

#7 Corey Kosak

Corey Kosak

    Advanced Member

  • Members
  • PipPipPip
  • 276 posts
  • LocationHoboken, NJ

Posted 07 March 2011 - 12:21 AM

I can't see the Problem at all with this code

Your first problem is that you have an infinite recursion on this code, on both the getter and setter side:

        public int MaxNumber
        {
            get { return MaxNumber; }
            set
            {
                MaxNumber = value > 9 ? 9 : value;
            }
        }

One way to solve this is to back it with a field, like so:

  private int maxNumber;

  public int MaxNumber
  {
    get { return maxNumber; }
    set
    {
      maxNumber = value > 9 ? 9 : value;
    }
  }


#8 ItsDan

ItsDan

    Advanced Member

  • Members
  • PipPipPip
  • 101 posts

Posted 07 March 2011 - 12:38 AM

Also it's fairly common to forgo the formal property syntax and just use public variables, but it's certainly valid code once you address the other comments. Anyways part of the reason for the Java/VB 'confusion' was we were addressing different things. I think the other poster's explanation was a little technical, but accurate. When I said it was like VB I meant, if you're familiar with using VB.NET then that knowledge will translate more directly to C# since the .net libraries are identical between each. The way you knew to ask if there was a collection you could use means you're familiar with that set of classes, and that set is available to anything referencing the .net libraries. Whether they're in the microframework is the only place the learning curve should exist. I really wasn't addressing what it compiles to or alternative libraries from Oracle or any of that stuff which for a beginning programmer is less important than "how do I make it work"
Follow the adventures of the Box of Crappy Surplus

Total BOCS Traveled Distance: 9708 miles | States Visited: 5
Track the Box

#9 Nevyn

Nevyn

    Advanced Member

  • Members
  • PipPipPip
  • 1072 posts
  • LocationNorth Yorkshire, UK

Posted 07 March 2011 - 06:55 AM

So am I able to use any kind of Collection?

You can use ArrayList if you want, you simply have to use a cast when retrieving the object from the list.
class Test { ...}

ArrayList a = new ArrayList();
Test t = new Test();
a.Add(t);
.
.
.
t = (Test) a[4];    // Get an object from the list.
It's not as pleasant as generics but it should work.

regards,
Mark

To be or not to be = 0xFF

 

Blogging about Netduino, .NET, STM8S and STM32 and generally waffling on about life

Follow @nevynuk on Twitter


#10 Ruff

Ruff

    New Member

  • Members
  • Pip
  • 9 posts

Posted 07 March 2011 - 12:09 PM

Your first problem is that you have an infinite recursion on this code, on both the getter and setter side:

        public int MaxNumber
        {
            get { return MaxNumber; }
            set
            {
                MaxNumber = value > 9 ? 9 : value;
            }
        }

One way to solve this is to back it with a field, like so:

  private int maxNumber;

  public int MaxNumber
  {
    get { return maxNumber; }
    set
    {
      maxNumber = value > 9 ? 9 : value;
    }
  }


Thanks for that!!! I think it will solve a bunch of problems. The Tutorial I use (german http://openbook.gali...ting.de/csharp/) didn't make that clear, but as You told me now, it makes absolutely sense.Now it looks more like a VB.Net Property

Also it's fairly common to forgo the formal property syntax and just use public variables, but it's certainly valid code once you address the other comments. Anyways part of the reason for the Java/VB 'confusion' was we were addressing different things. I think the other poster's explanation was a little technical, but accurate. When I said it was like VB I meant, if you're familiar with using VB.NET then that knowledge will translate more directly to C# since the .net libraries are identical between each. The way you knew to ask if there was a collection you could use means you're familiar with that set of classes, and that set is available to anything referencing the .net libraries. Whether they're in the microframework is the only place the learning curve should exist. I really wasn't addressing what it compiles to or alternative libraries from Oracle or any of that stuff which for a beginning programmer is less important than "how do I make it work"


I can't forget this Property if I have logic in the setter, and youre right that VB helps me to understand internal class libs, while java helps more for the syntax. Am I right, that everything in C# 'methods' is passed as 'Copy' like in VB 'ByVal' and If I wanna have a reference I have to declare VB's 'ByRef' simply as 'ref Type Name' or 'out Type Name'?


You can use ArrayList if you want, you simply have to use a cast when retrieving the object from the list.

class Test { ...}

ArrayList a = new ArrayList();
Test t = new Test();
a.Add(t);
.
.
.
t = (Test) a[4];    // Get an object from the list.
It's not as pleasant as generics but it should work.

regards,
Mark

thx, that is what I have expected. So I can put i.e. a Test.Class instance as a[0] and Test2.class instance as a[1]?
Should I prefer to use Arrays(I think performance can get important programming Micocontrollers)?

#11 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 07 March 2011 - 12:47 PM

Ruff, an ArrayList is just an Array (i.e. object[]), but wraps it by adding some useful function like Add and Remove. "Pure" arrays aren't modifiable, but ArrayList resize automatically the underlying array upon the real usage.

Yep: you may set any kind of object in the ArrayList, since is actually an object[].

About parameters. In C# everything is considered by reference, but when the parameter inherits from ValueType (e.g. a struct), there is a copy of the object.
This sounds slightly different that Java, because there the native types don't derive from "object", but in C# does. Formally, I like more the C# approach, so *any* object inherits from "object"...
It worths noting that *NOT* all inherits from object, even in C#: read this...
http://blogs.msdn.co...rom-object.aspx

Hope it helped.
Cheers
Mario
Biggest fault of Netduino? It runs by electricity.

#12 Ruff

Ruff

    New Member

  • Members
  • Pip
  • 9 posts

Posted 08 March 2011 - 03:38 PM

Ruff, an ArrayList is just an Array (i.e. object[]), but wraps it by adding some useful function like Add and Remove. "Pure" arrays aren't modifiable, but ArrayList resize automatically the underlying array upon the real usage.

Yep: you may set any kind of object in the ArrayList, since is actually an object[].

About parameters. In C# everything is considered by reference, but when the parameter inherits from ValueType (e.g. a struct), there is a copy of the object.
This sounds slightly different that Java, because there the native types don't derive from "object", but in C# does. Formally, I like more the C# approach, so *any* object inherits from "object"...
It worths noting that *NOT* all inherits from object, even in C#: read this...
http://blogs.msdn.co...rom-object.aspx

Hope it helped.
Cheers
Mario

thx for the answer. So my assumption is right, that I can put different Objects into the same ArrayList.

What I'm not yet understanding 100% is these 'struct' ValueType.
I know structs from C, But there it makes sense for the lack of Objects. Are ValueTypes the same that in Java is known as Raw-Rypes?Does it mean I can derive from ValueTypes to design my own?

another question: does one 'bool' take more space in Ram than a byte? Does it make sense to use bytes instead of ints?
I have an issue that compiler won't compile this statement:
byte mybyte = 100
mybyte = mybyte + x > 255 ? mybyte + x - 255 : mybyte+x; // where x stands for example for 150
Compiler tells me that byte is explicity convertet and cannot be converted implicit.
The problem in this line is i.e. the '255' -> recognized as an int while 100 in instantiation makes no problems at all.

#13 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 08 March 2011 - 04:01 PM

Ruff,

Instead of:
byte mybyte = 100 
mybyte = mybyte + x > 255 ? mybyte + x - 255 : mybyte+x; // where x stands for example for 150
Try this:
byte mybyte = 100 
mybyte = mybyte + x > 255 ? (byte)(mybyte + x - 255) : (byte)(mybyte+x); // where x stands for example for 150
While the ++ and -- operators "roll over" in C#, you need to manually cast values and/or expressions which could result in a value outside the range of the result's type.

Chris

#14 awaiK

awaiK

    Advanced Member

  • Members
  • PipPipPip
  • 90 posts

Posted 08 March 2011 - 04:04 PM

[...] What I'm not yet understanding 100% is these 'struct' ValueType.
I know structs from C, But there it makes sense for the lack of Objects. Are ValueTypes the same that in Java is known as Raw-Rypes?Does it mean I can derive from ValueTypes to design my own? [...]

Hi,

no, structs in .NET are not the same as raw types in Java, as far as I know. There is no real equivalent for structs in Java. The only thing which is similiar to structs are primitive types in Java.
In .NET primitive types (= structs) can also include Methods.

You can make your own struct by using the struct keyword instead of the class keyword.

Regarding the ValueType class:

[...] Aside from serving as the base class for value types in the .NET Framework, the ValueType structure is generally not used directly in code. However, it can be used as a parameter in method calls to restrict possible arguments to value types instead of all objects, or to permit a method to handle a number of different value types. [...]



#15 CW2

CW2

    Advanced Member

  • Members
  • PipPipPip
  • 1592 posts
  • LocationCzech Republic

Posted 08 March 2011 - 04:16 PM

byte mybyte = 100
mybyte = mybyte + x > 255 ? mybyte + x - 255 : mybyte+x; // where x stands for example for 150

You can also use modulus operator:

mybyte = (byte)((mybyte + x) % 255);


#16 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 08 March 2011 - 04:29 PM

Well, I don't know exactly some low-level features. I try to read some interesting blogs like the Eric's one (often is much more a puzzling test, instead of a spare time readings).
http://blogs.msdn.com/b/ericlippert/

I also don't know so much Java, but I knew there are two kinds of "integers", for example: one is "native" (raw, I guess) and the other is an object (where you may apply methods).
In C# there's not difference: you may use "int" and "Int32". The first syntax is C# and it's compiled always as the "Int32" object.
I think that the blog of Eric contains a lot of useful answers for you.

About the "bool".
I think that a bool is a 32-bit field, masked to a flag (here in Venezia is Carnival :) ), but that's my hypothesis.
I've done some test time ago, and I've seen that manipulating types other than a 32-bit, it takes much more instructions (so time) to compute. That's on a 32-bit machine, of course.
You may try to yourself: declare two variables, an int and a byte, then make some basic operation (e.g. increment, addition, etc). When you peek the IL-op codes that the compiler generates, you'll see that the int is much more close to the CPU other than the byte.

Finally, about the code.
C# tries to consider the integer numbers as "int", so you should write:

byte mybyte = 100;
mybyte = mybyte + x > 255 ? (byte)(mybyte + x -255) : (byte)(mybyte+x);
even "x" is a byte.
NOTE: by writing "mybyte+x", you *know* that it's an integer addition. If it would be a byte, it won't get never a value higher than 255 and the condition would be always false.

Instead, if you must have a byte, I'd suggest:

byte mybyte = 100;
mybyte = (byte)(mybyte + x);
or *more correctly*:

byte mybyte = 100;
mybyte = unchecked((byte)(mybyte + x));
The "unchecked" keyword disables the overflow checking for the basic data operations. Normally that's the default, so you may discard it.

Hope it helped.
Cheers
Mario
Biggest fault of Netduino? It runs by electricity.

#17 Nevyn

Nevyn

    Advanced Member

  • Members
  • PipPipPip
  • 1072 posts
  • LocationNorth Yorkshire, UK

Posted 08 March 2011 - 06:26 PM

thx for the answer. So my assumption is right, that I can put different Objects into the same ArrayList.

Whilst you can put any type of object in the list, you need to make sure the object is the right type when you take it out. Consider the following:
class A {...}
class B {...}

A a = new A();
B b = new B();

ArrayList list = new ArrayList();
list.Add(a);
list.Add(B);

class A result;

result = (A) list[1];
This should raise an error as list element 1 is of type B and not type A. In order to get around this problem you need to check out the is and as keywords.

Regards,
Mark

To be or not to be = 0xFF

 

Blogging about Netduino, .NET, STM8S and STM32 and generally waffling on about life

Follow @nevynuk on Twitter


#18 Ruff

Ruff

    New Member

  • Members
  • Pip
  • 9 posts

Posted 09 March 2011 - 12:21 AM

You can also use modulus operator:

mybyte = (byte)((mybyte + x) % 255);


uhh I like that: Simple, short and clear. B)

Ruff,

Instead of:

byte mybyte = 100 
mybyte = mybyte + x > 255 ? mybyte + x - 255 : mybyte+x; // where x stands for example for 150
Try this:
byte mybyte = 100 
mybyte = mybyte + x > 255 ? (byte)(mybyte + x - 255) : (byte)(mybyte+x); // where x stands for example for 150
While the ++ and -- operators "roll over" in C#, you need to manually cast values and/or expressions which could result in a value outside the range of the result's type.

Chris

did I hear "roll over"?? thats interesting! What else in C# rolls over?

Thanks for all the help. These questions came up as I tried to write a library for DotMatrixes. I want to share this code here if it is working. I have some issues debugging arrays. I have lots of 'flags' to store. These Flags currently look for example like this:
byte[][] A = 
{ 
  new byte[]{1, 1, 1, 1, 1},
  new byte[]{1, 0, 0, 0, 1},
  new byte[]{1, 0, 0, 0, 1},
  new byte[]{1, 0, 0, 0, 1},    
  new byte[]{1, 1, 1, 1, 1},
  new byte[]{1, 0, 0, 0, 1},
  new byte[]{1, 0, 0, 0, 1}
}
And this for the whole Alphabet. I considered to store them as bool but
bool[][] A = 
{
  new bool[]{true, true, true, true, true},
  new bool[]{true, false, false, false, true},
  new bool[]{true, false, false, false, true},
  new bool[]{true, false, false, false, true},
  new bool[]{true, true, true, true, true},
  new bool[]{true, false, false, false, true},
  new bool[]{true, false, false, false, true},
}
isn't very readable while it didn't feel to be faster.

While my Code is working if I'm only showing one Letter, or simply "switch" them it won't work if I want to let them 'run' over the screen. There have to be a big logical issue in my shift method, nut I can't find it since debugger is only showing me '?' as value for a byte!

I think memory is very limited in comparation with a "normal" .Net system or even a mobile device. What can I do to a) see whats going on and b ) not burning amounts of Bytes?
An idea I had was to store one int as a column taking its binary Value as flags. But I could't find any useful implementation or API to get or set binary values like I can do in C. I only find same Syntax as in C for Hex using 0x..
To convert them manually store them as String and parse it..... <_< :blink:
isn't binary data the closest 'type' to a processor?

I'll uploaded the as-is state. I hope it is clear enaugh. Feel free to ask, correct or suggest anything you like.
I had every bit[][] as ref in every method before, because i thought that caused the problem in the shiftPattern method

Attached Files



#19 Nevyn

Nevyn

    Advanced Member

  • Members
  • PipPipPip
  • 1072 posts
  • LocationNorth Yorkshire, UK

Posted 09 March 2011 - 07:28 AM

I have lots of 'flags' to store. These Flags currently look for example like this:

Not sure if this is implemented in NETMF (it is part of the full .NET), but there is a Flags attribute which can be applied to enums (can't verify it at the moment as I'm away from my N+ dev machine). This might make your code more readable and could make it more compact depending upon what you are doing.
[Flags]
public enum Sides = { Left = 1, Right = 2, Top = 4, Bottom = 8 }
You can then use these with the bitwise operators to provide combinations:
Sides leftAndRight = Sides.Left | Sides.Right;
As I say, this will need verifying to see if it is in NETMF.
Regards,
Mark

To be or not to be = 0xFF

 

Blogging about Netduino, .NET, STM8S and STM32 and generally waffling on about life

Follow @nevynuk on Twitter


#20 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 09 March 2011 - 07:51 AM

Just to point it...
What's wrong in the following code?

byte[] vector = new byte[256];

for (byte i = 0; i < 256; i++)
{
  vector[i] = i;
}
The problem is that the for-loop will never completes, because once i=255, its increment rolls it to zero again. So the condition is always satisfied.

I'd rather use int anywhere and bytes only for raw-streaming. I guess there's no overhead of memory, nor loss of performance.

Cheers
Mario
Biggest fault of Netduino? It runs by electricity.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.