对于某些16位值,通过pyserial发送到Arduino-Mega2560的两个字节未正确接收

时间:2019-06-30 16:44:26

标签: python arduino pyserial arduino-ide

我正在使用0xABCD库将16位值从PC发送到 Arduino-mega2560 。我已将16位值分成两个8位值,以便通过com端口发送。 Arduino代码只是发送回给它的值相同。如果16位中的4位(0x8000, 0xA000, 0xFFFF中的任何一位)超过7(例如,如果A或B或C或D中的任何一位超过7),例如:void setup() { // put your setup code here, to run once: analogReference(DEFAULT); // initialize both serial ports: Serial.begin(115200); for(int i=54;i<70;i++) pinMode(i, INPUT); // pinMode(potPin2, INPUT); for(int i=22;i<37;i++) pinMode(i, OUTPUT); } void loop() { // put your main code here, to run repeatedly: int inn=1;uint8_t in;uint16_t VAL,mask=0x0001;uint16_t VOL=0x0000; if (Serial.available() >= 2) { VAL = Serial.read() << 8; //read MSB into VAL VAL |= Serial.read(); uint8_t LSB=VAL; uint8_t MSB=VAL>>8; Serial.write(1); Serial.write(MSB); Serial.write(LSB); } } 等,我得到一个不同的结果从Arduino获得价值!以下是Arduino代码,

from os import system, name
ar=serial.Serial("COM8",115200)
time.sleep(1)
def getv():
    while (ar.inWaiting()<2): #Do while loop waiting for data   
        pass
    val=ar.read(2)
    s=int(val.hex(), 16)
    #s=binascii.hexlify(val).decode('utf-8')
    return(s)

stat=0
def setp(pos):
    global cur,stat
    if(stat==0):
        msb=chr(int(pos/256))
        lsb=chr(pos%256)
        ar.write(msb.encode())
        ar.write(lsb.encode())
        while (ar.inWaiting()<1): #Do while loop waiting for data   
            pass
       a=ar.read()
       cur=0x0000
    else:
        cur=cur|pos

setp(0x8000)
print(getv())
ar.close()

以下是Python代码

0x8000

对于32768,实际上是十进制的49792,代码给出A0A0。 对于4112049824),代码给出public async Task<T> PostResponse<T>(string weburl, string jsonstring) where T : class { var Token = App.TokenDatabase.GetToken(); string ContentType = "application/json"; var token = string.Format("Token token={0}", Token.access_token); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); try { var result = await client.PostAsync(weburl, new StringContent(jsonstring, Encoding.UTF8, ContentType)); if(result.StatusCode == System.Net.HttpStatusCode.OK) { var JsonResult = result.Content.ReadAsStringAsync().Result; try { var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult); return ContentResp; } catch { return null; } } } catch { return null; } return null; } 。 我正在犯什么错误?

0 个答案:

没有答案